I'm wondering what is the difference between using a JSONObject and JSONTokener to parse a JSON string.
I have seen examples where either of these classes were used to parse a JSON string.
For example, I parsed a JSON string like this:
JSONObject object = (JSONObject) new JSONTokener(jsonString).nextValue();
return object.getJSONObject("data").getJSONArray("translations").
getJSONObject(0).getString("translatedText");
But I also see examples where they simply use a JSONObject class (without using JSONTokener) to parse it:
String in;
JSONObject reader = new JSONObject(in);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
I read the description on this page, but still don't really get the difference. Is one better than the other performance wise and when should a JSONTokener be used?
Thanks!
Related
I want to store a particular value of JSONobject response in one variable.
My JSON response is a string:
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
And from this response I want to retrieve the mobile number.
Can Anyone help?
Your Json is
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
Parse it Easily
JSONObject jsonObject= new JSONObject(json_response);
String mobile= jsonObject.optString("mobile");
Use asynchttpclient library. Its easy to use and parse values.
add this line in app gradle,
compile 'com.loopj.android:android-async-http:1.4.9'
Then,
Let, String s = "{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}";
JSONObject jsonObject = new JSONObject(s);
String username = jsonObject.optString("username");
String mobile = jsonObject.optString("mobile");
String password = jsonObject.optString("password");
You need to do something like the below:
final JSONObject jsonObject = new JSONObject(response);
if (jsonObject.length() > 0) {
String mobile = jsonObject.optString("mobile");
Log.e("TAG", "mobile:"+mobile);
}
Im using JsonObject to parse a response from an API, the problem is that the resulting String have double quotes, how to get string with no quotes?
JsonElement jelement = new JsonParser().parse(response);
JsonObject jobject = jelement.getAsJsonObject();
String authorization = jobject.get("authorization").toString();
Log.d("mensa","parseado jwt :"+authorization);
so my response looks like...
parseado jwt :"eyJ0eXAiOiJKV1QiLCJhbGciO..."
Actual Json response
{
"authorization": "eyJ0eXAiOiJKV1..."
}
what is the right way to parse this string so i dont get it wrapped with double quotes?
I believe you are using GSON library. No need to trim out your result, gson provide methods for that. try this
String authorization = jobject.get("authorization").getAsString();
Refer Gson API Doc : JsonElement
You are getting Object from Json and then converting to String. jobject.get("authorization").toString(); try to get String.
String authorization = jobject.getString("authorization");
Just trim out the quotes: authorization = authorization.substring(1, authorization.length() - 1)
Edit: You should actually use the getString() method as it will return the actual content as a string, however, the above still works as a quick workaround.
This might be a simple question, so sorry for that. I'm trying to develop a radio app for my internet radio station. I'm using JSON format for the requests (Example JSON) to get information from my station. For example the "title" tag. I want to get this information.
My first try:
JSONObject data = response.getJSONObject("data");
songname.setText(data.getString("title"));
But the problem is that I cannot get this information. What can I do? Thanks in advance.
As your JSON do like this
JSONObject josnOBJ = new JSONObject(response);
JSONArray jArray = josnOBJ.getJSONArray("data");
JSONObject jsonData = null;
String title = null;
for (int i=0; i < jArray.length(); i++)
{
try {
jsonData = jArray.getJSONObject(i);
title= jsonData .optString("title");
} catch (JSONException e) {
// Oops
}
}
songname.setText(title);
You could use some generic JSON parsers instead of manual work. Eg: https://github.com/bajicdusko/AndroidJsonProvider
Just create model class regarding your json content. Check examples in README on github url.
Hope i could help.
You can use GSON library in case you have lot of values to fetch from JSON ,that would take care of everything for you.
I know how to access to json. Now I get a json response like that:
"2014-02-16T20:27:54+00:00"
https://openligadb-json.heroku.com/api/last_change_date_by_league_saison?league_shortcut=bl1&league_saison=2013
this is not a JSONArray and has no Name. How can I access it?
It is not json formatted data. If you need it in json, you can generate it by yourself like this :
JSONObject json = new JSONObject();
json.put("data", "2014-02-16T20:27:54+00:00" );
json.toString(); // { "data" : ""2014-02-16T20:27:54+00:00" } it is json
In other case you can work with this data as typical String. It depends on what you need to achieve.
Good luck!
I am having android with converts the JSON string to its original java object.
I am returning the List from REST server and it converts List into JSON format like this.
{"offerRideResult":[{"date":"06-APR-13 10.00.00.000000 AM","destination":"B","id":"57","PTripId":"87","req":"false","source":"A","srNo":"0","username":"Chinmay"},{"date":"06-APR-13 10.00.00.000000 AM","destination":"B","id":"1","PTripId":"88","req":"false","source":"A","srNo":"0","username":"chinmay91"}]}
On the client side that is android I am using the following method to convert it into java object.
try{
JSONObject obj=new JSONObject(response);
JSONArray arr=null;
arr=obj.getJSONArray("offerRideResult");
List<OfferRideResult> offerRideResult=new ArrayList<OfferRideResult>();
for(int i=0;i<arr.length();i++)
{
OfferRideResult res=new OfferRideResult();
res.setId(arr.getJSONObject(i).getInt("id"));
res.setPTripId(arr.getJSONObject(i).getInt("PTripId"));
res.setSrNo(arr.getJSONObject(i).getInt("srNo"));
res.setDate(arr.getJSONObject(i).getString("date"));
res.setSource(arr.getJSONObject(i).getString("source"));
res.setDestination(arr.getJSONObject(i).getString("destination"));
res.setReq(arr.getJSONObject(i).getBoolean("req"));
res.setUsername(arr.getJSONObject(i).getString("username"));
offerRideResult.add(res);
}
}catch(JSONException e)
{
System.out.println("Exception :- "+e);
}
It works fine when JSON format has two or more than two records but with on record it throws the following exception when input is like this.
{"offerRideResult":{"date":"05-APR-13 10.00.00.000000 AM","destination":"B","id":"1","PTripId":"89","req":"false","source":"A","srNo":"0","username":"chinmay91"}}
Error!!!org.codehaus.jettison.json.JSONException: JSONObject["offerRideResult"] is not a JSONArray
Can anybody please point my mistake or how can I deal with array of length one?
Thanks
but with on record it throws the following exception
use JSONObject.optJSONObject or JSONObject.optJSONArray for extracting next item from main JSONObject.try it as:
JSONObject obj=new JSONObject(response);
JSONArray arr=null;
JSONObject jsonobj=null;
// get offerRideResult JSONArray
arr=obj.optJSONArray("offerRideResult");
if(arr==null){
// means item is JSONObject instead of JSONArray
jsonobj=obj.optJSONObject("offerRideResult");
}else{
// means item is JSONArray instead of JSONObject
}
Because the json with only one results is not an array it's not going to be read correctly by getJSONArray()
either you can make your json string more like:
{"offerRideResult":[{"date":"05-APR-13 10.00.00.000000 AM","destination":"B","id":"1","PTripId":"89","req":"false","source":"A","srNo":"0","username":"chinmay91"}]}
or read it in as a single object like #ρяσѕρєя K proposes.