Android 2.3.3
I am integrating Twitter API into my android application. I am using Twitter4j.
I could get the tweets for a particular user, using the below code.
Paging paging = new Paging(1, 40);
List<twitter4j.Status> statuses = twitter.getUserTimeline("xxx", paging);
Log.d(Const.TAG,"Showing Timeline.");
for (twitter4j.Status status : statuses) {
String rawJSON = DataObjectFactory.getRawJSON(status);
}
My requirement is that I need to parse the JSON String (rawJSON), to get some other values like, published date and so on.
I am pretty new to JSON parsing esp., with converting things to JSON. All i know in the above code is that, String rawJSON = DataObjectFactory.getRawJSON(status); converts the Status Object to a String and I can view it by logging it.
How do I convert this String to a JSONObject or a JSONArray? Can someone provide me with a sample code?
I tried the below code, but it gives an exception
try {
JSONObject tweet = new JSONObject(rawJSON);
JSONArray textArray = tweet.getJSONArray("text");
String text = textArray.getString(0);
Log.d(Const.TAG, "Text = "+text);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d(Const.TAG, "Error while converting string to json");
e.printStackTrace();
}
Here's my code to parse a Twitter4j Status. This example get the language of the tweet.
//Status To JSON String
String statusJson = DataObjectFactory.getRawJSON(status);
//JSON String to JSONObject
JSONObject JSON_complete = new JSONObject(statusJson);
//We get another JSONObject
JSONObject JSON_user = JSON_complete.getJSONObject("user");
//We get a field in the second JSONObject
String languageTweet = JSON_user.getString("lang");
I got a way to get values from Status object without the need to convert it into JSON. Of course this is very basic, by I overlooked it.People who have trouble getting values from Status object, can look at this.
You can get all the values by using the object of Status.
For example, if "status" is an object of Status, we can get the text of the tweet, by using, status.getText() and the user value by using status.user() and so on. Just work on the status object a bit and you will find all the values you need.
Related
I am trying to parse this json.
However, it is not working ...
I want to parse expected_departure_time of all the buses such as 4 , 15, C1, 4A in departure
this is my code which is not working.
try{
String str = response.getString("departures");
JSONArray jsonArray = response.getJSONArray(str);
JSONObject bus = jsonArray.getJSONObject(0);
String four = bus.getString("expected_departure_time");
textView.append(four);
}catch (JSONException e){
e.printStackTrace();
}
JSON
https://transportapi.com/v3/uk/bus/stop/6090282/live.json?app_id=d7180b02&app_key=47b460aac35e55efa666a99f713cff28&group=route&nextbuses=yes
The error you're making is that you're considering "departures" as a JsonArray, which is not the case in your JSON example, it is a JsonObject (Which in my opinion is a poor way of constructing this Json).
Anyway, you will have to get all the JsonObjects inside the "departure" JsonObject by doing this:
try
{
String jsonString=response.toString();
JSONObject jObject= new JSONObject(jsonString).getJSONObject("departures");
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONArray innerJArray = jObject.getJSONArray(key);
//This is your example, you can add a loop here
innerJArray(0).getString("expected_departure_time");
}
}
catch (JSONException e)
{ e.printStackTrace(); }
If you need to use the transport API for other features, to convert JSON strings to Java objects, you can map automatically by using GSON.
Follow the instructions from Leveraging the gson library and map any response you want from this API.
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to display information retrieved from server using php in an android app,I have retrieved the information in a String with json formatting here is the retrieve code and php code.
PHP code
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
//Getting values
$username = $_POST['username'];
require_once('dbConnect.php');
$sql = "SELECT * FROM `employee` WHERE username='$username'";
$result=mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
echo json_encode($row);
}
Android Retrieve code
#Override
protected String doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
HashMap<String,String> params1= new HashMap<>();
params1.put(Config.KEY_EMP_UN,mUsername);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Config.URl_RET, params1);
return res;
// TODO: register the new account here.
}
#Override
protected void onPostExecute(final String success) {
Toast.makeText(Main2Activity.this,success,Toast.LENGTH_LONG).show();
final TextView Textview1 = (TextView)findViewById(R.id.textView);
Textview1.setText(success);
}
This retrieves info in format shown in below image
What is want to do is extract Name,Designation,Salary,Password and display them in separate TextView.How can I do that?
Take your server response and parse it like this
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("name")) {
String name=jsonObject.getString("name");
}
if (jsonObject.has("designation")) {
String designation=jsonObject.getString("designation");
}
if (jsonObject.has("salary")) {
int salary=jsonObject.getInt("salary");
}
if(jsonObject.has("password")){
String password=jsonObject.getString("password");
}
}catch (Exception e) {
}
you have to parse the json :
JSONObject jsonObject=new JSONObject(success);
//key value for eg : name,salary etc
// now do whatever you want to do
jsonObject.getString("your key value");
There are lots of possible duplicates to this question, so I recommend closing this question after reading this answer.
What you have in here is a JSON response and in order to parse information in JSON, you have to use a JSON parser. Libraries like Gson, Jackson, Moshi will be able to do this.
If you're using Gson, you have to generate model classes of the response which can be written manually or auto-generated using jsonschema2pojo. Once Gson parses your JSON, you can use your model classes getters to access data.
Links to tutorials
https://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
Youtube video
https://www.youtube.com/watch?v=y96VcLgOJqA
I'm using Retrofit 2 to call API in Android App. I have a API, using POST, which have a String param in Query Tag. I do everything like doc suppose and I test this API successfully in Test Page. I can run another API correctly so the problem is not the way I use Retrofit 2.
Here is my interface:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query("list") String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
Here is my implementation:
ArrayList<String> id = new ArrayList<>();
id.add("4782947293");
JSONArray jsonArray = new JSONArray(id);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("list", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String list = jsonObject.toString();
Log.e(TAG, "list: " + list);
apiInterface.getListFriend(21, list, 1,1,"AHHIGHTJGI").enqueue(new Callback<GetListFriendDataResponse>() {
#Override
public void onResponse(Call<GetListFriendDataResponse> call, Response<GetListFriendDataResponse> response) {
Log.e(TAG, " response code: "+ response.code());
}
#Override
public void onFailure(Call<GetListFriendDataResponse> call, Throwable t) {
}
});
I always get response code: 400 when use this API.
I'm focusing the "list" var. "list" is a JSON text but I wonder if method "jSon.toString()" is right to get a String from a JSONObject, which can using in Retrofit 2. List param form is:{"list":["12332"]} .
Please help me!
Questions
1) Why you are creating JSONObject and JSONArray on your own?
2) You are creating string using whatever you are creating json.
Eg: {list:["123","456"]}
you are trying pass whole json, I think, instead you need to pass just the array of string to the list key.
Request Sending
{
list:["123","456"]
}
suppose the above json is the request you want to send to server
Now, create model class goto http://jsonschema2pojo.org and paste your json and select json and gson at right side and click on preview.
It will show the classes to map you json to model. Use this model class to set the list to the key in your json
I found my problem. The JSON text contains some special character so I need to convert them to URL encode.
Correct request URL like this:
http://54.169.215.161:8080/users/29/add_friend?list=%7B%22list%22%3A%5B%2215536%22%5D%7D&platform=google
By using Retrofit 2, it uses the URL:
http://54.169.215.161:8080/users/29/add_friend?list={%22list%22:[%2215536%22]}&platform=google
So I get Bad Request Response code.
Retrofit 2 also provides method to convert char sequence to URL encode but it 's not enough. So I don't use Retrofit 's convert method by using this code: encode= true.
so my interface is:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query(value = "list",encoded = true) String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
And I manually convert JSON text to URL encode by code:
list = list.replace("{", "%7B");
list=list.replace("]", "%5D");
list=list.replace("[", "%5B");
list=list.replace(":", "%3A");
list=list.replace("}","%7D");
list = list.replace("\"", "%22");
That's all. Now I can get data by using API.
Suggestion: If u have the same problem, check the URL retrofit return in response and compare to correct URL to see special character, which is not converted to URL encode.
I am writing an android application and currently i am getting a JSON reply:
{"Error":"User already exists"}
this is an example of the messages that i get returned
the part that i am after is : "User already exists" and i need to parse it.
The message is currently stored in a string so i would need to convert this to a JSONArray to then convert it to a JSONOject to then be able to call the getString().
what would be the best way to do this?
this may Helps You
String Respones= "{\"Error\":\"User already exists\"}";
try {
JSONObject jobj = new JSONObject(Respones);
String strError = jobj.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think you can do it directly with JSONTokener and JSONObject if you want ot use default andoid tools.
If you want better, look into the Jackson lib, it's very powerful, open source, kind of standard:
Android JSON Jackson Tutorial
Try this code
JSONArray jsonArray = new JSONArray(ResponseString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String result = jsonObject.getString("Error").toString().trim();
}
I had gone through a link on parsing Json data on Android, but didnt understand pretty much.
I am getting the following JSON String from my server.
I need to parse it and present it as a listview in my android app. ANy guidance or code snippet.?
Also since my Jason string has data for images, will the listview be able to display it properly?
My JSON String is:
{"results":{"result":[{"year":"2012","title":"The Amazing Spider-Man","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Marc Webb","rating":"7.3","cover":"http:\/\/i.media-imdb.com\/images\/SF1f0a42ee1aa08d477a576fbbf7562eed\/realm\/feature.gif"},
{"year":"2014","title":"The Amazing Spider-Man 2","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Marc Webb","rating":"7.3","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BMzk3MTE5MDU5NV5BMl5BanBnXkFtZTYwMjY3NTY3._V1._SX54_CR0,0,54,74_.jpg"},
{"year":"2002","title":"Spider-Man","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Sam Raimi","rating":"6.3","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BODUwMDc5Mzc5M15BMl5BanBnXkFtZTcwNDgzOTY0MQ##._V1._SX54_CR0,0,54,74_.jpg"},
{"year":"2007","title":"Spider-Man 3","details":"http:\/\/www.imdb.com\/title\/tt1872181","director":"Sam Raimi","rating":"7.5","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BMjE1ODcyODYxMl5BMl5BanBnXkFtZTcwNjA1NDE3MQ##._V1._SX54_CR0,0,54,74_.jpg"},
{"year":"2004","title":"Spider-Man 2","details":"http:\/\/www.imdb.com\/title\/tt1872181","director":"Sam Raimi","rating":"6.8","cover":"http:\/\/i.media-imdb.com\/images\/SFa26455c07afc3c94f52e95de50d5d814\/realm\/tv_series.gif"}]}}
Make Arraylist of All Fields and Write below function to parse above json, it will solve your problem.
ArrayList<String> year, title, details, director, rating, cover;
// For Parse Login Response From Server
public void mParseResponse() throws UnknownHostException {
year=new ArrayList<String>();
title=new ArrayList<String>();
details=new ArrayList<String>();
director=new ArrayList<String>();
rating=new ArrayList<String>();
cover=new ArrayList<String>();
try {
JSONObject jObject = new JSONObject(EntityUtils.toString(entity));
JSONObject jsonobjresults = jObject.getJSONObject("results");
JSONArray jsonarrayresult = jsonobjresults.getJSONArray("result");
for(int i=0;i<jsonarrayresult.length(); i++){
JSONObject mJsonObj = jsonarrayresult.getJSONObject(i);
year.add(mJsonObj.getString("year"));
title.add(mJsonObj.getString("title"));
details.add(mJsonObj.getString("details"));
director.add(mJsonObj.getString("director"));
rating.add(mJsonObj.getString("rating"));
cover.add(mJsonObj.getString("cover"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
read this tutorial http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html.
You can use gson library of Google to parse json.
you need to create java classes to store json values
passs that class ref to gson libary. It has simple methods.
chec this doc