I am creating a JSON request as followed:
JSONObject request = new JSONObject();
request.put("ID", "35");
request.put("password", "password");
List<JSONObject> fieldList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
fieldList.add(new JSONObject()
.put("unitid", "unitid " + i)
.put("price", "Price " + i));
}
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", fieldList)
);
String requestString = request.toString();
The value of requestString variable should be :
{
"ID": "35",
"password": "password",
"unitsummary": {
"unitsummarydetail": [
{
"price": "Price 0",
"unitid": "unitid 0"
},
{
"price": "Price 1",
"unitid": "unitid 1"
},
{
"price": "Price 2",
"unitid": "unitid 2"
}
]
}
}
But it is :
{
"ID": "35",
"password": "password",
"unitsummary": {
"unitsummarydetail": "[{\"unitid\":\"unitid 0\",\"price\":\"Price 0\"}, {\"unitid\":\"unitid 1\",\"price\":\"Price 1\"}, {\"unitid\":\"unitid 2\",\"price\":\"Price 2\"}]"
}
}
It is converting the unitsummarydetail as string.
I have tried but didn't find similar issue or any solution on internet.
Is there any issue in my code or this is the behavior of library?
Any ideas or solution code snippets are welcome.
Thanks.
Use JSONArray instead of ArrayList.
JSONObject request = new JSONObject();
request.put("ID", "35");
request.put("password", "password");
JSONArray fieldList = new JSONArray();
for (int i = 0; i < 3; i++) {
fieldList.put(new JSONObject() .put("unitid", "unitid " + i) .put("price", "Price " + i));
}
request.put("unitsummary", new JSONObject() .put("unitsummarydetail", fieldList) );
String requestString = request.toString();
Output:
{"ID":"35","password":"password","unitsummary":{"unitsummarydetail":[{"unitid":"unitid
0","price":"Price 0"},{"unitid":"unitid 1","price":"Price
1"},{"unitid":"unitid 2","price":"Price 2"}]}}
change your code
from
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", fieldList));
to
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", new JSONArray(fieldList)));
Crazy !!!!
JsonArray treatIdArray = new JsonArray(); // this one will result string : "["id", "id"]"
JSONArray treatIdArray = new JSONArray(); // this one will result array : ["id", "id"]
They are 2 different Json, lol, com.google.gson.JsonArray vs org.json.JSONArray and it took me almost a day. Oh my God !!!!
you could create a JSON array unitsummarydetail and add all the json objects unitsummary in a for loop
Related
I have been trying to extract array elements from my JSON, but unable to, so far.
I have the following JSON:
{
"Sample JSON": [{
"Title": "Title1",
"Audit": [{
"auditId": "01",
"type": "sampleType",
"auditText": "sampleText",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "02",
"type": "sampleType2",
"auditText": "sampleText2",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
},
{
"Title": "Title2",
"Audit": [{
"auditId": "03",
"type": "sampleType3",
"auditText": "sampleText3",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "04",
"type": "sampleType4",
"auditText": "sampleText4",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
}
]
}
I want to extract the array elements of the array 'answer'.
I get exception in the line indicated in comment in the method below:
public void getAudit(String myJSON) {
auditList = new ArrayList<AuditList>();
String title;
String auditId;
String type;
String auditText;
ArrayList<String> answer = new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONArray jssArray = jsonObj.getJSONArray("Sample JSON");
int jsonArrLength = jssArray.length();
for (int i = 0; i < jsonArrLength; i++) {
JSONObject jsonChildObj = jssArray.getJSONObject(i);
title = jsonChildObj.getString("Title");
JSONArray jssArray1 = jsonChildObj.getJSONArray("Audit");
for (int i1 = 0; i1 < jssArray1.length(); i1++) {
JSONObject jsonChildObj1 = jssArray1.getJSONObject(i1);
type = jsonChildObj1.optString("type");
auditText = jsonChildObj1.optString("auditText");
auditId = jsonChildObj1.optString("auditId");
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
//Getting exception in above line
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
AuditList aList = new AuditList();
aList.setQuesId(auditId);
aList.setQuesText(auditText);
aList.setQuesTypw(auditType);
aList.setAnswer(answer);
aList.setCategoryName(title);
auditList.add(aList);
}
}
.
.
.
.
.
}
I found the exception occurring in the line indicated above using the debugger.
Couldn't find a way to extract array elements of the array 'answer'.
Please help.
if(!jsonChildObj1.get("answer").toString().equals("")){
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
}
The exception that occurred to you because of Empty Data (""). To Prevent this validate it and getJSONArray(). refer
The way I do this kind of stuff is by going to this link and then paste my json there and get my class. After that, you can go and add Gson to your gradle by adding this line to your build.gradle:
compile 'com.google.code.gson:gson:2.6.2'
Then just create an instance of the created class that you just created and convert json into your target class:
NewClass classObject = new Gson().fromJson(YOUR_JSON, NewClass.class);
I want to remove json value from below json file .
This is my json object :
{
"Approximation": {
"name": "Approximation",
"description": [
"Approximation",
"Approximation",
"Approximation"
],
"video": [
"evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd",
"evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd",
"evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"
]
}
}
and this is what I'm trying
Code :
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
jsonArr.remove(i);
children = new ArrayList<ChildrenEvent>();
et = new Events(jsonObj.optString("name"));
ct = new ChildrenEvent(jsonObj.optString("description"));
langs.add(et);
children.add(ct);
}
I am not sure what you are trying to achieve here. You don't need to remove the key "Approximation" to get the data.
This is how you parse this JSON.
{
"Approximation": {
"name": "Approximation",
"description": ["Approximation", "Approximation", "Approximation"],
"video": ["evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd", "evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd", "evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"]
}
}
Code,
JSONObject mainObj = new JSONObject(json_string);
JSONObject appproxObj = mainObj.getJSONObject("Approximation");
// Parse name
String name = appproxObj.getString("name");
et = new Events(name);
langs.add(et);
// Parse descriptions
JSONArray descriptions = appproxObj.getJSONArray("description");
children = new ArrayList<ChildrenEvent>();
for (int i = 0; i < descriptions.length(); i++ ) {
String description = descriptions.getString(i);
ct = new ChildrenEvent(description);
children.add(ct);
}
Still if you need the JSON without key "Approximation", the variable appproxObj has the JSON without the key.
There is a method in JsonObject, that is remove(). It will help you to remove any key from jsonObject;
Use this:-
jsonObject.remove("key");
Hi guys i have this JSONObject I'm having hard time to parse it.
Here's the JSON,
{
"query": {
"count": 2,
"created": "2016-11-07T15:29:47Z",
"lang": "en-US",
"results": {
"rate": [{
"id": "USDINR",
"Name": "USD/INR",
"Rate": "66.7700",
"Date": "11/7/2016",
"Time": "3:27pm",
"Ask": "66.8000",
"Bid": "66.7700"
}, {
"id": "USDEUR",
"Name": "USD/EUR",
"Rate": "0.9060",
"Date": "11/7/2016",
"Time": "3:29pm",
"Ask": "0.9065",
"Bid": "0.9060"
}]
}
}
}
As you can see above there are two "Rate" I want to store first "Rate" to a String array called Result[0] and second "Rate" to Result[1].
Here what I'm trying.
JSONObject object = new JSONObject(JSON);
JSONObject rateObject = object.getJSONObject("rate");
JSONArray rateArray = rateObject.getJSONArray("Rate");
result[0] = rateArray.getString(0);
result[1] = rateArray.getString(1);
I know maybe I'm doing this like stupid. So please help me out.
To Get the array I would try this:
JSONObject object = new JSONObject(JSON);
JSONObject rateObject = object.getJSONObject("results");
JSONArray rateArray = rateObject.getJSONArray("rate");
And then use a for to read all objects in the array:
int length = rateArray.length();
for (int i =0; i < length; i++){
JSONObject rate = rateArray.getJSONObject(i);
String rateResult = rate.getString("Rate");
}
Your formatted JSON looks like this
{
"query":{
"count":2,
"created":"2016-11-07T15:29:47Z",
"lang":"en-US",
"results":{
"rate":[
{
"id":"USDINR",
"Name":"USD/INR",
"Rate":"66.7700",
"Date":"11/7/2016",
"Time":"3:27pm",
"Ask":"66.8000",
"Bid":"66.7700"
},
{
"id":"USDEUR",
"Name":"USD/EUR",
"Rate":"0.9060",
"Date":"11/7/2016",
"Time":"3:29pm",
"Ask":"0.9065",
"Bid":"0.9060"
}
]
}
}
}
To get the rate array you have to this
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray rateArray = jsonObject.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
Then query rate array like this
JSONObject rateJSON = (JSONObject)rateArray.get(index);
String id = rateJSON.getString("id"); //Or any other field of rate
Anthony,
You need to go from the root element ( query ) to the "rate" node :
JSONArray rates = object.getJSONObject("query").getJSONObject("results").getJSONArray("rate")
result[0] = rates.getJSONObject(0).get("Rate")
result[1] = rates.getJSONObject(1).get("Rate")
you need to do this
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject queryObj = jsonObj.getJSONObject("query");
JSONObject resultObj = queryObj.getJSONObject("results");
JSONArray rateArr = resultObj.getJSONArray("rate");
result[0] = rateArr.getJSONObject(0).getString("Rate");
result[1] = rateArr.getJSONObject(1).getString("Rate");
Try this:
JSONArray rateArray = new JSONObject(JSON)
.getJSONObject("query")
.getJSONObject("results")
.getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
I've got problem with parsing JSON. I've got response from webservice like this :
{
"data": {
"1": [
{
"id": "2",
"name": "Szelki bezpieczeństwa",
"quantity": "1",
"note": null,
"picture_id": null,
"code": "CCCCCCCCCCCCCC"
},
{
"id": "3",
"name": "Kalosze do brodzenia, wysokie lub biodrowe",
"quantity": "2",
"note": "Do wymiany",
"picture_id": null,
"code": "DDDDDDDDDDDDDD"
}
],
"2": [
{
"id": "1",
"name": "Spodnie dla pilarza z ochroną przed przecięciem, klasa min. 1 (wg PN-EN 381-5)",
"quantity": "2",
"note": "Uszkodzone",
"picture_id": null,
"code": "DAAD086F690E1C36"
}
]
}
}
I try to parse it into PART object and add it to List but somewhere I'm making mistake because object is not being parsed.
public void onResponse(String response) {
Log.e(TAG, "onResponse WHOLE: " + response);
try {
JSONObject responseJSONObject = new JSONObject(response);
String arrayString = responseJSONObject.getJSONArray("data").toString();
JSONArray responseJSONArray = new JSONArray(arrayString);
Part tempCarEquipment;
int index = 1;
for (int i = 0; i < responseJSONArray.length(); i++,index++) {
JSONObject object = responseJSONArray.getJSONObject(index);
JSONArray response2 = object.getJSONArray(Integer.toString(index));
String id = object.getJSONObject(Integer.toString(i)).getString("id");
String name= object.getJSONObject(Integer.toString(i)).getString("name");
String quantity= object.getJSONObject(Integer.toString(i)).getString("quantity");
String picture_id= object.getJSONObject(Integer.toString(i)).getString("picture_id");
String code= object.getJSONObject(Integer.toString(i)).getString("code");
tempCarEquipment = new Part(name,quantity,"",picture_id,code,id,"",0);
wholeList.add(tempCarEquipment);
Log.e(TAG, "wholeList: " + wholeList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance fo every help! :)
JSON Parsing
You have to use the iterator for this kind of response
basic example of iterator is in this link.
You are trying to parse map as an array here:
String arrayString = responseJSONObject.getJSONArray("data").toString();
Try something like this instead:
List<JSONArray> objects = new ArrayList<>();
Iterator<String> keys = responseJSONObject.getJSONObject("data").keys();
while(keys.hasNext()) {
objects.add(responseJSONObject.getJSONObject("data").get(keys.next());
}
// rest of your stuff
Alternatively, consider using GSON to parse JSON responses using POJOs.
I'm trying to get the inner object of a json array (my jargon could be incorrect) that looks like this:
{
"News": {
"0": {
"name": "nytimes",
"fullName": "The New York Times",
"text": "#OwenPerry We heard from the owner of the house and corrected the article http://t.co/8GEgGy7",
"timestamp": "2011-08-15 12:20:36"
},
"1": {
"name": "HuffingtonPost",
"fullName": "Huffington Post",
"text": "Look out! New Zealand Skier chased by angry bulls - http://t.co/L0PZkx4",
"timestamp": "2011-08-15 12:19:04"
}
}
}
My code to retrieve the inner objects looks like this:
JSONArray category = json.getJSONArray("News");
JSONArray innerobj = category.getJSONArray(0);
for (int i = 0; i < innerobj.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = innerobj.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", c.getString("fullName") + "\n(#"
+ c.getString("name") + ") ");
map.put("text",
c.getString("text") + "\n - "
+ c.getString("timestamp"));
mylist.add(map);
}
Any Ideas on what i'm doing incorrectly?
You don't have JSONArray, but JSONObjects. Your JSONObject structure is:
Main JSONObject, which contains 1 JSONObject - "news"
"news" contains two JSONObjects, "0" and "1"
Each of those objects have four fields - "name", "fullname", "text" and "timestamp"
Consider:
JSONObject jobj = new JSONObject(yourString);
JSONObject newsobj = jobj.getJSONObject("news");
JSONObject firstOne = newsobj.getJSONObject("0"); // this is the object "0"
....