I am trying to parse a JSON string in Android which is dynamical. It is a very simple JSON structure. Similar to the following:
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
But sometimes I don't get some keys. For example, the key "b" could be missing. Then my code generates a JSONParser Exception. And the further JSON string could not parsed.
So is there any way to ignore missing keys? I tried optString(); but that only works in String case, what about JSONObject and JSONArray? optJSONArray() and optJSONObject() don't work.
Any idea or solution?
I think the easiest way is to use
GSON!
You simply create a plain old java object (POJO) representing the data you want and let GSON do the rest. If the value doesn't exist in the json string, it'll be set to the "default" for that type (usally null, but is 0 for ints, false for booleans etc...)
To include in your Android Studio project:
compile 'com.google.code.gson:gson:2.2.4'
Also take a look at this page, with particular attention to the "Object Examples" heading for how to use GSON.
You can find dynamic key using belo
String jsonString = "{ \"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4, \"e\": 5 }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject issueObj = new JSONObject(jsonString);
Iterator iterator = issueObj.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
Integer value = (Integer) issueObj.get(key);
Log.d(TAG,"value: "+value);
}
} catch (JSONException e) {
e.printStackTrace();
}
Or you can use GSON.
You can try convert that JSONObject to a Map using GSON, like the following:
String json1 = "{\n" +
" \"a\": 1,\n" +
" \"b\": 2,\n" +
" \"c\": 3,\n" +
" \"d\": 4,\n" +
" \"e\": 5\n" +
"}";
Gson gson1 = new Gson();
Type type1 = new TypeToken<Map<String, Integer>>(){}.getType();
Map<String, Integer> myMap1 = gson1.fromJson(json1, type1);
In your build.gradle file:
compile 'com.google.code.gson:gson:2.3.1'
Related
I have JSON data to parse. The structure is not fixed, and sometimes it comes as a single string and other times as an array.
Currently, we are using the GSON library for parsing JSON, but are facing problems when it comes as an array.
For example:
1. {"msg":"data","c":300,"stat":"k"}
2. {
"msg": [
" {\"id\":2,\"to\":\"83662\",\"from\":\"199878\",\"msg\":\"llll\",\"c\":200,\"ts\":1394536776}"
],
"c": 200,
"stat": "k",
"_ts": 1394536776
}
In the example above, sometimes I get msg as a string and sometimes as an array.
Can anyone help me? If I decide to use JSON parsing, it will be very tedious because I have around 20+ API to parse and each API contains a mininum of 50 fields.
You can use JSONObject and JSONArray classes instead of GSON to work with JSON data
for the first example
String jsonStr = "{\"msg\":\"data\",\"c\":300,\"stat\":\"k\"}";
JSONObject jsonObj = new JSONObject(jsonStr);
String msg = jsonObj.getString("msg");
Integer c = jsonObj.getInteger("c");
String stat = jsonObj.getString("stat");
For the second example
String jsonStr = ... // "your JSON data";
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonArr = jsonObj.getJSONArray("msg");
JSONObject arrItem = jsonArr.getJSONObject(0);
//and so on
Also JSONObject class have method opString, opArray which does not throw exception if data you trying to get is not exist or have a wrong type
For example
JSONArray arr = jsonObj.optJSONArray("msg");
JSONObject msg = null;
if (arr != null) {
msg = arr.getJSONObject(0)
} else {
msg = jsonObj.getJSONObject("msg");
}
You can use Google GSON lib for directly parse the json to class object. This is easy and accurate.Okay do one thing both time code is different, if the code is 300 directly parse the json object without GSON. if the code is 200 the use the GSON (Define the similar java class)
String c= json.getString("c");
if(c.equals("300")
String message = status.getString("msg");
There are two ways to parce JSON.
Manually using Android OS JSON Parser Android JSON Parsing And Conversion
Using GSON Library [Library] (https://code.google.com/p/google-gson/downloads/list). This easy to handle if you know all the parameters and models of json response.
Refer the code snippet below to deserialize your json using Google's Gson library without exceptions.
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("msg");
if(elem.isJsonArray()) { //**Array**
ArrayList<MyMessage> msgList = gson.fromJson(elem.toString(), new TypeToken<List<MyMessage>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), MyMessage.class);
} else { //**String**
String note = elem.toString();
}
MyMessage class
public class MyMessage {
String to;
String from;
String msg;
int id;
int c;
long ts;
// Setters and Getters
}
I don't see what's wrong with my JSON, I'm getting the error that it cannot be converted to JSONObject. I searched on the forum but I can't find the answer.
Code (to parse):
JSONObject json = new JSONObject(result.toString().replace("\\", " "));
JSONArray jArray = json.getJSONArray("timetable");
for(int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
String class_school = json_data.getString("class");
String teacher = json_data.getString("teacher");
String subject = json_data.getString("subject");
String room = json_data.getString("room");
timetList.add(new TimeTable(subject, class_school + " " + teacher + " " + " " + room));
}
JSON:
{"timetable":[{"teacher":"Woh","subject":"BVH","room":"017","change":"no"},{"teacher":"Rrl","subject":"BI","room":"045","change":"no"},{"teacher":"Ajg","subject":"WI","room":"019","change":"no"},{"teacher":"Sgh","subject":"NE","room":"119","change":"no"},{"teacher":"Rom","subject":"FA","room":"116","change":"no"},{"teacher":"Her","subject":"GS","room":"127","change":"no"},"free","free"]}
Logcat:
03-29 15:06:11.356: E/error(822): Value free at 6 of type java.lang.String cannot be converted to JSONObject
Seems to me, you're trying to parse last two entries ("free","free") to a JSONObject. If for some reason you need to add empty entries use {}.
Consider using optString instead of getString (or use try catch statment to handle exception)
Problem is in String. Your JSON String is broken and it is reason of
Value free at 6 of type java.lang.String cannot be converted to
JSONObject
Look at your String:
{
"timetable": [
{"teacher":"Woh","subject":"BVH","room":"017","change":"no"},
{"teacher":"Rrl","subject":"BI","room":"045","change":"no"},
{"teacher":"Ajg","subject":"WI","room":"019","change":"no"},
{"teacher":"Sgh","subject":"NE","room":"119","change":"no"},
{"teacher":"Rom","subject":"FA","room":"116","change":"no"},
{"teacher":"Her","subject":"GS","room":"127","change":"no"},
"free","free"
]
}
You need to remove this unexpected sequence:
"free","free"
and last comma in JSONObject with teacher's value Her and it should work.
Your string is valid JSON; however
JSONObject json_data = jArray.getJSONObject(i);
assumes that the entity at array position i be a JSON object. "free" is a string, which is not an object type in JSON (not surrounded by {}), getJSONObject(i) throws this exception when you try to make an object out of a string.
The strings can be extracted with jArray.getString(i), but the real trick is determining the type of the entity at position i. You can try a generic jArray.get(i) and then introspect the returned value to determine its type.
I've a json output which returns something like this :
[
{
"title":"facebook",
"description":"social networking website",
"url":"http://www.facebook.com"
},
{
"title":"WoW",
"description":"game",
"url":"http://us.battle.net/wow/"
},
{
"title":"google",
"description":"search engine",
"url":"http://www.google.com"
}
]
I am familiar with parsing json having the title object, but i've no clue about how to parse the above json as it is missing the title object. Can you please provide me with some hints/examples so i can check them and work on parsing the above code?
Note : I've checked a similar example here but it doesn't have a satisfactory solution.
Your JSON is an array of objects.
The whole idea around Gson (and other JSON serialization/deserialization) libraries is that you wind up with your own POJOs in the end.
Here's how to create a POJO that represents the object contained in the array and get a List of them from that JSON:
public class App
{
public static void main( String[] args )
{
String json = "[{\"title\":\"facebook\",\"description\":\"social networking website\"," +
"\"url\":\"http://www.facebook.com\"},{\"title\":\"WoW\",\"description\":\"game\"," +
"\"url\":\"http://us.battle.net/wow/\"},{\"title\":\"google\",\"description\":\"search engine\"," +
"\"url\":\"http://www.google.com\"}]";
// The next 3 lines are all that is required to parse your JSON
// into a List of your POJO
Gson gson = new Gson();
Type type = new TypeToken<List<WebsiteInfo>>(){}.getType();
List<WebsiteInfo> list = gson.fromJson(json, type);
// Show that you have the contents as expected.
for (WebsiteInfo i : list)
{
System.out.println(i.title + " : " + i.description);
}
}
}
// Simple POJO just for demonstration. Normally
// these would be private with getters/setters
class WebsiteInfo
{
String title;
String description;
String url;
}
Output:
facebook : social networking website
WoW : game
google : search engine
Edit to add: Because the JSON is an array of things, the use of the TypeToken is required to get to a List because generics are involved. You could actually do the following without it:
WebsiteInfo[] array = new Gson().fromJson(json, WebsiteInfo[].class);
You now have an array of your WebsiteInfo objects from one line of code. That being said, using a generic Collection or List as demonstrated is far more flexible and generally recommended.
You can read more about this in the Gson users guide
JSONArray jsonArr = new JSONArray(jsonResponse);
for(int i=0;i<jsonArr.length();i++){
JSONObject e = jsonArr.getJSONObject(i);
String title = e.getString("title");
}
use JSONObject.has(String name) to check an key name exist in current json or not for example
JSONArray jsonArray = new JSONArray("json String");
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonobj = jsonArray.getJSONObject(i);
String title ="";
if(jsonobj.has("title")){ // check if title exist in JSONObject
String title = jsonobj.getString("title"); // get title
}
else{
title="default value here";
}
}
JSONArray array = new JSONArray(yourJson);
for(int i = 0 ; i < array.lengh(); i++) {
JSONObject product = (JSONObject) array.get(i);
.....
}
"carMake": {
"Tata": [
"FIAT",
"INDICA VISTA",
"INDIGO XL"
],
"Hyndai": [
"SANTRO Xing",
"I10",
"I20",
"ACCENT",
"SONATA"
]
},
I just need to parse this part in my response. I tried with map but I am not getting it solved.
use gson.
http://code.google.com/p/google-gson/
You could try using a JSON Object parser.
Here's a link to an example http://www.jondev.net/articles/Android_JSON_Parser_Example
See the bellow example.
The response string is like this
String jsonStr = '{"menu": {' +
'"id": "file",' +
'"value": "File",' +
'"popup": {' +
'"menuitem": [' +
'{"value": "New", "onclick": "CreateNewDoc()"},' +
'{"value": "Open", "onclick": "OpenDoc()"},' +
'{"value": "Close", "onclick": "CloseDoc()"}' +
']' +
'}' +
'}}';
use the bellow code to parse the json String
// grabbing the menu object
JSONObject jsonObf=new JSONObject(jsonStr);
JSONObject menu = jsonObj.getJSONObject("menu");
// these 2 are strings
String id = menu.getString("id");
String value = menu.getString("value");
// the popop is another JSON object
JSONObject popup = menu.getJSONObject("popup");
// using JSONArray to grab the menuitems from under popop
JSONArray menuitemArr = popupObject.getJSONArray("menuitem");
// lets loop through the JSONArray and get all the items
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
Log.v(menuitemArr.getJSONObject(i).getString("value").toString());
Log.v(menuitemArr.getJSONObject(i).getString("onclick");
}
In your case, do the simple modifications to achieve the solution.
i m facing prob in parsing this obj
{
"id": 1909,
"permalink": "http:some url",
"title": "Voting begins for third phase of Bihar polls",
"excerpt": "some data.",
"date": "October 27, 2010 21:23",
"tags": [
"bihar",
"india-politics"
]
}
pls tell how to read tags value how to read value of tags
Lets say "jsonString" is equal to that example string
JSONObject json = new JSONObject(jsonString);
int id = json.getInt("id");
String permalink = json.getString("permalink");
JSONArray tags = json.getJSONArray("tags");
String firstTag = tags.getString(0);
You need to catch JSONExceptions and optionally check json.has("someproperty") before grabbing data.
u can use
Gson gson = new Gson();
List mylist = gson.fromJson(json, listtype);
u have to import gson jar which u can google it
In android Json classes are available, so no need to go elsewhere...
Step 1 : Init Json object with source string
JSONObject jObject = new JSONObject(srcString);
Step 2 : Init parent tag with another json object
if parent tag contains array the take JosnArray else JsonObject, in ur case suppose obj is parent tag then
JSONObject data = jObject.getJSONObject("obj");
Step 3 :
Now get String values
data.getString("id");
Or if array then
JSONArray dataArray = data.getJSONArray("tags");
JSONObject menuObject =dataArray.getJSONObject(0);
String firstvalue= menuObject.getString("first");
Use the JSONObject and its methods as Ian says above, however if you don't want your app to throw exceptions if any of the values are missing you can also use the 'opt' (Optional) methods, e.g.
JSONObject json = new JSONObject(jsonString);
String permalink = json.optString("permalink","");
Rather than throw an exception if 'permalink' is not found, it will return the second parameter, in this case an empty string.