JSON for Example:
{
"example_key1": {
"one": 1,
"two": 2,
"three": 3
},
"example_key2": [
{
"four": 4,
"five": 5,
"six": 6
}
]
}
Right now i am consuming one method from web service.That method is returning some JSON data like the above JSON example.
Here my problem is if some KEY values is missing from the JSON data, after consuming that method.(Say "example_key2" json value from the above json example is missing)
in the sense,
how can i recognize wether that key value is available or not?
You can check whether particular key is available or not by using has() method
For example:
if(myJSONObject.has("one")) {
num = myJSONObject.optString("one");
}
Use has method of JSONObject class
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
JSONObject j = new JSONObject("");
j.has("example_key2");
Related
I am getting a json array in API response which has different data types (String, Integer and Array) in same key (value) but getting error while parsing them with Retrofit:
{
"custom_attributes": [
{
"attribute_code": "description",
"value": "<p>Product Features:</p>\r\n<ul>\r\n<li>100% cotton</li>\r\n<li>Round neck</li>\r\n<li>Short sleeve</li>\r\n<li>Plastisol printing technique</li>\r\n<li>Small label on side of sleeve</li>\r\n</ul>"
},
{
"attribute_code": "short_description",
"value": "<p>100% cotton round neck short sleeve tee with plastisol printing technique</p>"
},
{
"attribute_code": "category_ids",
"value": [
"3",
"125"
]
},
{
"attribute_code": "special_price",
"value": true
},
{
"attribute_code": "size",
"value": 4
}
]
}
I can't understand what is the need of keeping your JSON format like this.
According json.org:
JSON is built on two structures:
• A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
• An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Tell me your requirement i will update your JSON and this problem will be solved once you will start getting updated JSON from erver.
Firstly store response in string like this
String response =apiresponse;
Then try this parsing methood without any thirdparty
get jsonobject from string response
JSONObject object=new JSONObject(response);
get jsonarray from json object
JSONArray jsonArray=object.getJSONArray("custom_attributes");
iterate json array till its length
for(int i=0;i<jsonArray.length;i++){
JSONObject newobject=jsonArray.getJSONObject(i);
Boolean valueBoolean;
String valueString;
String attribute_code=newObject.getString("attribute_code");
Object value=newObject.get("value");// get **value** key data in object
now check datatype of value key
if(value instanceof String){
valueString=value.toString(); //if value found string store in in value String
}else if(value instanceof Boolean){
valueBoolean=(Boolean)value; //if value found Boolean store it in valueBoolean
}
}
In the last its upto you , you may simply create a custom arraylist and save all details with datatype key
Working on a project where i am performing some operation based on instruction code. there are some json keys. where i am getting all the required values but have problem to get one among all. I am a initial level developer here.
Note : at everytime when i try to get instruction value in my android code i get 0.can anybody suggest me how should i go through now.
You can refer screenshot for my code.
From server I am getting proper json response.
{
"success": "true",
"error": "",
"result": [
{
"message": "Network is requesting permission to connect to your phone",
"instruction": 111,
"imei_no": "b2b5e4012e3c8b49",
"socket_user_id": "u566135811c9a2"
}
]
}
You are accessing the JSON value with not the correct key.
The correct way to get the key value is:
int instruction= json.getJSONArray("Result").getJSONObject(0).optInt("instruction")
Global version:
json.getJSONArray("Result").getJSONObject(index_of_array).optInt("instruction")
public long optLong (String name)
Returns the value mapped by name if it exists and is a long or can be coerced to a long, or 0 otherwise. Note that JSON represents numbers as doubles, so this is lossy; use strings to transfer numbers via JSON.
http://developer.android.com/reference/org/json/JSONObject.html#optJSONArray(java.lang.String)
Try this Hope this will Work!
final JSONObject obj = new JSONObject(response.toString());
final JSONArray array= obj.getJSONArray("result");
final int n = array.length();
for (int i = 0; i < n; ++i) {
final JSONObject result= array.getJSONObject(i);
System.out.println(result.getString("message"));
System.out.println(result.getString("instruction"));
}
It looks like you're not retrieving "result" from json. You'll need to retrieve result, which should give you an array, and then retrieve the first object of the array, in order to retrieve its property instruction.
Its a result of optInt method:
public int optInt(java.lang.String key)
Get an optional int value associated with a key, or zero if there is no such key
or if the value is not a number. If the value is a string, an >attempt will be made to evaluate it as a number.
You should get JsonArray "Result" and next get first JsonObject. Now, you can access to "instruction".
I found a lot of tutorials here, how to parse JSON Data of an JSON Array.
But my JSON File is a little bit complicate (for me). It has the following structure:
JSON File (excerpt)
{
"data": {
"schedule_id": {
"12": {
"name": "CP",
"d_id": [
"7"
]
},
"17": {
"name": "WT",
"d_id": [
"88",
"14"
]
}
}
}
}
Java Code (excerpt)
Info: I've parsed the json into "json" using HTTP GET in another Activity.
JSONObject dataJsonData = json.getJSONObject("data").getJSONObject("schedule_id");
Now I would parse through the ids using a "for"-loop:
ArrayList<String> parsedNameList = new ArrayList<String>();
for (int i = 0; i < idontknow; i++) {
String s = new Integer(i).toString();
parsedNameList.add(dateJsonData.getJSONObject(i).getString("name"));
}
This would add each value of "name" to the ArrayList.
But there are 2 problems:
1. The "schedule_id"s are messed up and incomplete. For example, there is no id "0" and, like in given json, the ids "13, 14, 15, 16" are missing.
2. The "schedule_id"s will be changed every day and will be mixed.
So I don't think, that I can use the predefined integer "i" because some integers aren't a "schedule_id". I could use this loop and would ignore empty entries in the ArrayList, but the JSON contains more than 200 ids - I think it would be more efficient, if there is another way to parse through this json.
I found some informations of the getJSONArray method, but the "d_id"s are Arrays - not the "schedule_ids".
Does anyone has an idea? Is there maybe a placeholder for the parameter of the getString method?
PS: Excuse my english, I'm from germany :)
I think this should work
Iterator keys = dataJsonData.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
String currentDynamicValue = dataJsonData .getString(currentDynamicKey);
parsedJsonList.add(currentDynamicValue );
}
Source: How to parse a dynamic JSON key in a Nested JSON result?
According to your context, it is better to change the json structure,if you have access to web service.
Request for json structure to be like this,
{
"data":{
"schedule":[
{
"id":12,
"name":"CP",
"d_id":[
"7"
]
},
{
"id":12,
"name":"CP",
"d_id":[
"7",
"88"
]
},
{
"id":200,
"name":"AT",
"d_id":[
"7",
"88"
]
}
]
}
}
Otherwise too much iteration can slow down you CPU.
I have a JSON as below
{
"shippingGroupListJson":[
{
"lineId":123,
"shippedTo":{
"country":"US"
},
"cartons":1,
"group":"4",
"shipInscription":{
"municipalInscription":"",
"inscriptionType":"",
"stateInscription":"",
"suframaInscriptionNumber":"",
"inscriptionBranch":"",
"contributorClass":"",
"inscriptionDigit":"",
"inscriptionNumber":""
},
"shipCartonDetails":[
],
"shippedContact":{
"firstName":"Mjjkk",
"email":"nob#gmail.com",
"fax":"--",
"phone":"80-121",
"lastName":"Henry"
},
"mobilityShipStatus":"Not Yet Shipped",
"shipDate":"13 Dec 2014"
},
{
"lineId":0,
"shippedTo":[
],
"cartons":0,
"group":"5",
"shipInscription":[
],
"shipCartonDetails":[
],
"shippedContact":[
],
"mobilityShipStatus":"",
"shipDate":"",
"shipStatus":""
}
]
}
If you see in this above JSON in key "shippedTo", when there is value , I get a JSON Object and when no value is present then i get a Blank JSONArray.
I need to fix this issue. I cannot communicate with the service team to change this as they won't make changes to it. Can any one tell me how can i do the required changes.
I know this is not the rite way, but i need to do something..
I tried using String.replaceAll(oldChar,newChar);
You say you are using GSON, in which case JsonArray and JsonObject are both subclasses of JsonElement.
But you do not say if you are using the DOM or Streaming technique with GSON.
You should show your parsing code, or the class that's being automatically used for the parsing.
In the meantime, based on what you have said, I would define my shippedTo field in my class as an Object. That should parse correctly (if using DOM), and after that you can analyse exactly what you have in that field.
Instead of:
private MyCountryType shippedTo;
Have:
private Object shippedTo;
You could simply check its type at runtime i.e
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
if(js.get("shippedTo") instanceof JSONArray){
//Treat it as an array
}
else{
//Treat it as a single json object
}
}
Furthermore if you need it as an JSONObject immaterial of it being a single element then do this to get your customized string
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
JSONObject js=new JSONObject(json_data);
if(js.get("shippedTo") instanceof JSONArray){
js.put("shippedTo",new JSONObject()); //purge the original array with this new blank element
}
else{
//Do your normal stuff
}
}
String curmodstring=jsPar.toString();
Hope you get the general idea.
I have a very basic ASP MVC application exposing a static list of publications (see code and result below).
Code:
public JsonResult Index()
{
List<Publication> list = new List<Publication>() {
new Publication() { Id = 1, Name = "War and Peace" },
new Publication() { Id = 2, Name = "Harry Potter" },
new Publication() { Id = 3, Name = "Cat in the Hat" }
};
return this.Json(list, JsonRequestBehavior.AllowGet);
}
Result:
[{"Id":1,"Name":"War and Peace"},{"Id":2,"Name":"Harry Potter"},{"Id":3,"Name":"Cat in the Hat"}]
When I attempt to consume it in Android I get the following error:
04-15 12:00:57.331: W/System.err(209): org.json.JSONException: A JSONObject text must begin with '{' at character 1 of [{"Id":1,"Name":"War and Peace"},{"Id":2,"Name":"Harry Potter"},{"Id":3,"Name":"Cat in the Hat"}]
I can remove the starting [ and ending ] and it stops the error from appearing. The other option is to put the { publications: logic at the beginning of the android code, but that seems like it should already be there.
How can I update the code in the MVC application to produce a "ready to be consumed" version of JSON?
Any help is greatly appreciated.
First, you shouldn't modify your json string when received, because it may mess up with the parsing.
Second, your Json string is in array format because it starts with [ and ends with ]. So, instead of using JSONObject, you should use JSONArray.
I recommend to use GSON. It's simple to use, fast and accurate.