Im trying to create a json array using the following code.
private JSONArray getJsonArray(String encodedString) {
JSONArray docArray = new JSONArray();
JSONObject docprops = new JSONObject();
JSONObject innerJson = new JSONObject();
JSONArray innerJsonArray = new JSONArray();
JSONObject inJobj = new JSONObject();
JSONArray outerJsonArray = new JSONArray();
SharedPreferences userDetails = getSharedPreferences("userdetails", Context.MODE_PRIVATE);
String session = userDetails.getString("session", "");
try {
innerJson.put("compliance_history_id", compliance_history_id);
docprops.put("file_size", fileSize);
docprops.put("file_name", fileName);
docprops.put("file_content", encodedString);
docArray.put(docprops);
innerJson.put("documents", docArray);
innerJson.put("completion_date", mCompletedDate.getText().toString());
innerJson.put("validity_date", JSONObject.NULL);
innerJson.put("next_due_date", mNextDueDate.getText().toString());
innerJson.put("remarks", mRemarks.getText().toString());
innerJsonArray.put("UpdateComplianceDetail");
innerJsonArray.put(innerJson);
inJobj.put("session_token", session);
inJobj.put("request", innerJsonArray);
outerJsonArray.put(session);
outerJsonArray.put(inJobj);
} catch (JSONException e) {
e.printStackTrace();
}
return outerJsonArray;
}
This is the json that my code is framing up..
[
"1-e4077f4a346440ecaeaf5f3387d47775",
{
"request": [
"UpdateComplianceDetail",
{
"remarks": "Remarks",
"next_due_date": "27-Mar-2016",
"completion_date": "31-may-2017",
"validity_date": null,
"documents": [
{
"file_name": "20160404_135811.jpg",
"file_size": 24,
"file_content": "iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAQAAAD8x0bcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mA"
}
],
"compliance_history_id": 49
}
],
"session_token": "1-e4077f4a346440ecaeaf5f3387d47775"
}
]
There might be multiple documents that are being uploaded so document array might contain multiple json objects within it. How can I be able to do so?
Is there by any means through which I can optimize the above code other than by using gson or jackson?
If documents is an array, iterate through the JSONArray object
JSONArray jsonObjectArray= updateComplianceDetailresponse.getJSONArray("documents");
LinkedList arrayCompliance=new LinkedList();
for(int count=0;count<jsonObjectArray.length();count++){
// iterate and get required elements
//Add to arrayCompliance LinkedList
}
If you might have multiple objects inside docArray then the below lines should be inside a for loop.
JSONObject docprops = new JSONObject();
docprops.put("file_size", fileSize);
docprops.put("file_name", fileName);
docprops.put("file_content", encodedString);
docArray.put(docprops);
SO depending on number of document objects you can iterate throught the for loop and for each iteration create a jsonObject and put it inside the docArray
Related
I have to send request body in Http request in below format:
{
"flag":false,
"Ids":["xyz","abc"]
}
I was trying like:
LinkedHashMap<String, Object> requestParamsMap = new LinkedHashMap<String, Object>();
requestParamsMap.put("flag",false);
ArrayList<String> IdList = new ArrayList<>();
IdList.add("xyz");
IdList.add("abc");
requestParamsMap.put("Ids", IdList.toString());
And then I was converting requestParamsMap to json string. But I am not getting request body in desired format.
I want to create a generalized method which can return me data in this type of format, so that I can use it throughout application.
Any help would be appreciated.. !!!
Do something like this:
JSONObject object=new JSONObject();
try {
object.put("flag","xyz");
JSONArray array=new JSONArray();
array.put("xyz");
array.put("abc");
object.put("Ids",array);
//added a log to see the output
Log.e("output",object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
object.toString() should contain exactly the json you want in string format. You can use a loop to populate the contents of the jsonArray or JSONObject depending on the number of items you have
Its not that though at all, output you want is JSONArray inside JSONObject and JSONObject inside another JSONObject. So, you can create them seperately and then can put in together. as below.
CODE
try {
JSONObject parent = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("lv1");
jsonArray.put("lv2");
jsonObject.put("mk1", "mv1");
jsonObject.put("mk2", jsonArray);
parent.put("root", jsonObject);
Log.d("output", parent.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
OUTPUT
{
"root": {
"mk1": "mv1",
"mk2": [
"lv1",
"lv2"
]
}
}
Im trying to frame a json array of following form
[
"1-35e03ac0b6ba442bb0d5fab3faef32fe",
{
"request": [
"UpdateComplianceDetail",
{
"remarks": "Remarks",
"next_due_date": "27-Mar-2016",
"completion_date": "04-Apr-2016",
"validity_date": null,
"documents": null,
"compliance_history_id": 23
}
],
"session_token": "1-35e03ac0b6ba442bb0d5fab3faef32fe"
}
]
Following is my code that i use to create json of above structure,
private JSONArray getJsonArray(String encodedString) {
JSONArray docArray = new JSONArray();
JSONObject innerJson = new JSONObject();
JSONArray innerJsonArray = new JSONArray();
JSONObject inJobj = new JSONObject();
JSONArray outerJsonArray = new JSONArray();
SharedPreferences userDetails = getSharedPreferences("userdetails", Context.MODE_PRIVATE);
String session = userDetails.getString("session", "");
try {
innerJson.put("compliance_history_id", 23);
docArray.put("null");
innerJson.put("documents", docArray);
innerJson.put("completion_date", "04-Apr-2016");
innerJson.put("validity_date", mValidityDate.getText().toString());
innerJson.put("next_due_date", mNextDueDate.getText().toString());
innerJson.put("remarks", mRemarks.getText().toString());
innerJsonArray.put("UpdateComplianceDetail");
innerJsonArray.put(innerJson);
inJobj.put("session_token", session);
inJobj.put("request", innerJsonArray);
outerJsonArray.put(session);
outerJsonArray.put(inJobj);
} catch (JSONException e) {
e.printStackTrace();
}
return outerJsonArray;
}
Following is the json that my code is creating,
[
"1-35e03ac0b6ba442bb0d5fab3faef32fe",
{
"request": [
"UpdateComplianceDetail",
{
"remarks": "Remarks",
"next_due_date": "27-Mar-2016",
"completion_date": "04-Apr-2016",
"validity_date": "null",
"documents": [
"null"
],
"compliance_history_id": 23
}
],
"session_token": "1-35e03ac0b6ba442bb0d5fab3faef32fe"
}
]
How can I be able to sort this out? I have put "null" within json array but its being recognised as a string and not as a null. also validity_date has to be null but it is a string "null"
docArray.length > 0 ? docArray : null evaluates the length of docArray. If it's length is greater than 0 (aka, it contains items), it will put the array as the content of documents. Otherwise it will put null.
Same thing for validity_date. isEmpty() checks for null or "" and if that's the case, null will be used in stead of the actual value of mValidityDate.getText().
private JSONArray getJsonArray(String encodedString) {
JSONArray docArray = new JSONArray();
JSONObject innerJson = new JSONObject();
JSONArray innerJsonArray = new JSONArray();
JSONObject inJobj = new JSONObject();
JSONArray outerJsonArray = new JSONArray();
SharedPreferences userDetails = getSharedPreferences("userdetails", Context.MODE_PRIVATE);
String session = userDetails.getString("session", "");
try {
innerJson.put("compliance_history_id", 23);
innerJson.put("documents", docArray.length > 0 ? docArray : JSONObject.NULL);
innerJson.put("completion_date", "04-Apr-2016");
String validityDate = mValidityDate.getText().toString();
innerJson.put("validity_date", validityDate.isEmpty() ? JSONObject.NULL : validityDate.toString());
innerJson.put("next_due_date", mNextDueDate.getText().toString());
innerJson.put("remarks", mRemarks.getText().toString());
innerJsonArray.put("UpdateComplianceDetail");
innerJsonArray.put(innerJson);
inJobj.put("session_token", session);
inJobj.put("request", innerJsonArray);
outerJsonArray.put(session);
outerJsonArray.put(inJobj);
} catch (JSONException e) {
e.printStackTrace();
}
return outerJsonArray;
}
Try using JSONObject.NULL
reference:
http://developer.android.com/reference/org/json/JSONObject.html#NULL
How do you set a value to null with org.json.JSONObject in java?
I have some JSON with the following structure:
{
"items":[
{
"product":{
"product_id":"some",
"price_id":"some",
"price":"some",
"title_fa":"some",
"title_en":"Huawei Ascend Y300",
"img":"some",
"has_discount_from_price":"0",
"discount_from_price":null,
"type_discount_from_price":null,
"has_discount_from_product":"0",
"discount_from_product":null,
"type_discount_from_product":null,
"has_discount_from_category":"0",
"discount_from_category":null,
"type_discount_from_category":null,
"has_discount_from_brand":"0",
"discount_from_brand":null,
"type_discount_from_brand":null,
"weight":null,
"features":[
{
"feature_value":"#000000",
"feature_id":"some",
"feature_title":"some"
},
{
"feature_value":"some",
"feature_id":"1652",
"feature_title":"some"
}
]
},
"number":1,
"feature_id":"56491,56493",
"price_inf":{
"has_discount":0,
"discount_type":0,
"final_price":"400000",
"value_discount":0
},
"cart_id":13
}
]
}
I'm trying to access the elements "product_id" and "price_id" with the following Java code:
try{
JSONArray feedArray=response.getJSONArray("items");
for (int i=0;i<feedArray.length();i++){
JSONObject feedObj=feedArray.getJSONObject(i);
JSONObject pro=feedObj.getJSONObject("product");
Product product = new Product();
product.setPrice(pro.getDouble("price_id"));
product.setTitle_fa(pro.getString("price_id"));}}
but i see product not found error.what is wrong in my parser?
First of all your JSON is valid. So no worries there.
Now regarding your problem, because you haven't posted the logs so I can't tell what the exact problem is. But using this code snippet you can get the desired values.
try {
JSONArray itemsJsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < itemsJsonArray.length(); i++){
JSONObject itemJsonObject = itemsJsonArray.getJSONObject(i);
JSONObject productObject = itemJsonObject.getJSONObject("product");
String productId = productObject.getString("product_id");
String priceId = productObject.getString("price_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Validate and create Pojo for your json here
use
Data data = gson.fromJson(this.json, Data.class);
follow https://stackoverflow.com/a/5314988/5202007
By the way your JSON is invalid .
you are getting a json object from your response not json array you need to make following changes
JSONObject temp =new JSONObject(response);
JSONArray feedArray=temp.getJSONArray("items");
Try converting response string to JSONObject first
try{
JSONObject temp =new JSONObject(responseString); // response is a string
JSONArray feedArray=.getJSONArray("items");
....
}
You may try to use GSON library for parsing a JSON string. Here's an example how to use GSON,
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
Ineed to post data in JSON format as shown below And the size of the array is not
constant. it depends on the user.
{
"info": [
{
"Name": "foo1",
"Number": 123
},
{
"Name": "foo2",
"Number": 124
},
{
"Name": "foo2",
"Number": 125
}
]
}
I tried to create in the following way
JSONObject parent = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject childObj = new JSONObject();
childObj.put("Name", etName.getText()).toString();
childObj.put("Number", etNumber.getText()).toString();
jArray.put(childObj);
parent.put("info",jArray);
but i'm unable to get it and I also tried in this way like example 6.1 but there is no method like add for JSONArray. So how can post my data. Please help me.
Thanks.
I'm not sure exactly what your question is but I'd typically do something like this to create the JSON string that you are looking for (the example below is using the org.json reference implementation from http://www.json.org/java/index.html):
JSONObject parent = new JSONObject();
JSONArray infoArray = new JSONArray();
for(int i = 0; i < SOMEARRAY.length; i++)
{
JSONObject childObj = new JSONObject();
childObj.put("Name", etName.getText());
childObj.put("Number", etNumber.getText());
infoArray.put(childObj);
}
parent.put("info", infoArray);
String encodedJsonString = parent.toString();
I don't understand why you're calling toString() after putting stuff into childObj.
Anyway, this code should work:
JSONObject parent = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject childObj = new JSONObject();
try
{
//create first child
childObj
.put("Name", "foo1")
.put("Number", 123);
//insert it into the array
jArray.put(childObj);
//... repeat for all remaining elements
//attach the array to the parent
parent.put("info",jArray);
}
catch (JSONException e)
{
e.printStackTrace();
}
Then, to get your JSON as a string for POSTing just call parent.toString();
I want parse json url,my json url contains following structures
{"content":{"item":[{"category":"xxx"},{"category":"yy"} ]}}
how to read this structure,anybody knows give example json parser for that.
Thanks
This code will help you to parse yours json.
String jsonStr = "{\"content\":{\"item\":[{\"category\":\"xxx\"},{\"category\":\"yy\"} ]}}";
try {
ArrayList<String> categories = new ArrayList<String>();
JSONObject obj = new JSONObject(jsonStr);
JSONObject content = obj.getJSONObject("content");
JSONArray array = content.getJSONArray("item");
for(int i = 0, count = array.length();i<count;i++)
{
JSONObject categoty = array.getJSONObject(i);
categories.add(categoty.getString("category"));
}
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject can do the parsing.
You need to use the org.json's package.
Example:
For an object:
JSONObject json = new JSONObject(json_string);
For an array:
JSONArray json = new JSONArray(json_string);