How to create JSON Object using String? - java

I want to create a JSON Object using String.
Example :
JSON {"test1":"value1","test2":{"id":0,"name":"testName"}}
In order to create the above JSON I am using this.
String message;
JSONObject json = new JSONObject();
json.put("test1", "value1");
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 0);
jsonObj.put("name", "testName");
json.put("test2", jsonObj);
message = json.toString();
System.out.println(message);
I want to know how can I create a JSON which has JSON Array in it.
Below is the sample JSON.
{
"name": "student",
"stu": {
"id": 0,
"batch": "batch#"
},
"course": [
{
"information": "test",
"id": "3",
"name": "course1"
}
],
"studentAddress": [
{
"additionalinfo": "test info",
"Address": [
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":36
}
],
"verified": true,
}
]
}
Thanks.

org.json.JSONArray may be what you want.
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);
json.put("course", array);
message = json.toString();
// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}

In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)

If you use the gson.JsonObject you can have something like that:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)

String jsonString = "{'element1':'value1','element2':{'id':0,'name':'testName'}}";
JsonObject jsonObject = (JsonObject) JsonParser.parseString(jsonString);

Underscore-java can create json from an object.
import com.github.underscore.U;
String message = U.objectBuilder()
.add("course", U.arrayBuilder()
.add(U.objectBuilder()
.add("id", 3)
.add("information", "test")
.add("name", "course1")
))
.add("name", "student")
.toJson();
System.out.println(message);
// {
// "course": [
// {
// "id": 3,
// "information": "test",
// "name": "course1"
// }
// ],
// "name": "student"
// }

Related

get a value from a json object (Google map distance)

hello I'm trying t get the distance from a JSON object
{
"destination_addresses": [
"Rabat, Morocco"
],
"origin_addresses": [
"Marrakesh, Morocco"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "324 km",
"value": 323624
},
"duration": {
"text": "3 hours 24 mins",
"value": 12233
},
"status": "OK"
}
]
}
],
"status": "OK"
}
I succeeded to get the elements object but I can't get the distance
org.json.JSONException: No value for distance
at org.json.JSONObject.get(JSONObject.java:389)
at com.application.zarbagaskazay.colivoiturage.testMApsActivity$1.onResponse(testMApsActivity.java:66)
at com.application.zarbagaskazay.colivoiturage.testMApsActivity$1.onResponse(testMApsActivity.java:56)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
here is the code
public void onResponse(JSONObject response) {
try {
JSONArray rows = response.getJSONArray("rows");
JSONObject elements=rows.getJSONObject(0);
// JSONObject cc= elements.getJSONObject("distance");
System.out.println(elements.get("distance"));
button.setText(elements.get("distance").toString());
} catch (JSONException e) {
e.printStackTrace();
}
In my suggestion:
You can replace
System.out.println(elements.get("distance"));
with
System.out.println(elements.getJSONArray("elements").getJSONObject(0).getJSONObj
ect("distance"));
Above sop will print/extract "distance" json value.
{"text":"324 km","value":323624}
Hope it works at your end too!
JSONObject jsonObject = new JSONObject("YOUR RESPONSE STRING");
JSONArray jsonArray = jsonObject.getJsonArray("rows");
JSONArray jsonArray_elements =jsonArray.getJsonObject(0).getJsonArray("elements");
JSONObject jsonObject_distance =
jsonArray_elements.get(0).getJsonObject("distance");
String text = jsonObject_distance.getString("text");
String value = jsonObject_distance.getString("value");

How to get a child attribute from JSONObject Java

I have a problem in my code where I need to print a child attribute from a JSONObject. Actually, I want to have the attribute values in a JSONArray because of some purposes.
<--So far I did-->
String preStringSingle = responseSingle.body().string(); // has the JSONObject
JSONObject resultsJObject = new JSONObject(preStringSingle);
JSONArray resultsJArray1 = resultsJObject.optJSONArray("data");
System.out.println(resultsJArray1);
<--JSONObject-->
"status": true,
"locale": "en-US",
"error_code": null,
"message": "OK",
"data": [
{
"service_list_access_mode": 0,
"service_list_domain": "http://www.hotsalesmarket.com",
"service_list_auth_method": 0,
"service_list_auth_user": null,
"service_list_auth_password": null,
"http_method": "GET",
"map_service_lists": [
{
"path": "sdfm.assets/assets/cameras/5799.jpg",
"service_item_id": 5799
},
{
"path": "dsf.assets/assets/cameras/5798.jpg",
"service_item_id": 5798
},
{
"path": "sdfsdf.assets/assets/cameras/6701.jpg",
"service_item_id": 6701
}
]
}
],
"timestamp": "2017-06-20T03:46:38Z"
}
I wanted to get all the details in the child attribute "map_service_lists".
<--Desired output-->
{
"path": "sdfsdf.assets/assets/cameras/5799.jpg",
"service_item_id": 5799
},
{
"path": "/sdfsdfs.assets/assets/cameras/5798.jpg",
"service_item_id": 5798
},
{
"path": "/sdfsdf.assets/assets/cameras/6701.jpg",
"service_item_id": 6701
}
You just have to continue like you did, but additional level down the hierarchy:
JSONArray data = resultsJObject.optJSONArray("data");
JSONObject firstData = data.optJSONObject(0);
JSONArray services = firstData.optJSONArray("map_service_lists");
System.out.println(services);
(Remove the array brackets from the result if you don't want them).
String preStringSingle = responseSingle.body().string();
JSONObject resultsJObject = new JSONObject(preStringSingle);
JSONArray resultsJArray1 = resultsJObject.optJSONArray("data");
JSONObject j = new JSONObject(resultsJArray1.get(0).toString());
JSONArray resultsJArray2 = j.optJSONArray("map_service_lists");
System.out.println(resultsJArray2);

Retrieve value Json field

I know that we have a lot of document on that but in my case I can't apply it.. I have a JSON file like that :
{
"Status": {
"Code": 0,
"Message": "Search OK"
},
"Applications": {
"Application": [{
"Id": 123,
"Name": "Bob"
},
...
]
}
}
I want to retrieve the value of the field "Name".
My code :
String jsonData = readFile("test.json");
JSONObject jobj = new JSONObject(jsonData);
JSONObject jobj2 = (JSONObject) jobj.get("Applications");
JSONArray jarr = new JSONArray(jobj2.getJSONArray("Application").toString());
After that I don't know what to do.. How can I resolve my problem?
Thanks a lot.
For this json:
{
"Status": {
"Code": 0,
"Message": "Search OK"
},
"Applications": {
"Application": [{
"Id": 123,
"Name": "Bob"
}]
}
}
Your code can looks like:
jsonObject
.getJSONObject("Applications")
.getJSONArray("Application")
.getJSONObject(0)
.getString("Name")

Add a new property to a specific json node using gson

I am exploring gson and wanted to check if I can remove and add elements. I have the below json
{
"header": {
"timeStamp": "2016-02-09T15:22:36.107-08:00",
"uniqueid": "321ef660",
},
"body": {
"search": {
"searchId": 9206422282,
"DateFrom": "2016-04-15T00:00:00-07:00",
"DateTo": "2016-06-24T00:00:00-07:00"
}
},
"amount": [
{
"amount": 73.704285,
"currency": "USD"
},
"amountagain": {
"amount": 96.791435,
"currency": "USD"
},
"winners": null,
"pgoodId": null,
},
and now I want to add a new element under body like :
{
"header": {
"timeStamp": "2016-02-09T15:22:36.107-08:00",
"uniqueid": "321c5690-1d2e-4403-9c31-029cc47ef660",
},
"body": {
"search": {
"searchId": 9206422282,
"DateFrom": "2016-04-15T00:00:00-07:00",
"DateTo": "2016-06-24T00:00:00-07:00"
"AddANewFieldHere" : **"2016-04-18"**
}
}
when I do
JsonObject jsonObject = new JsonObject();
try {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader("src/main/resources/search.json"));
jsonObject = jsonElement.getAsJsonObject();
} catch (FileNotFoundException e) {
} catch (IOException ioe){
}
// jsonObject.get("checkin");
jsonObject.addProperty("AddANewFieldHere","2016-04-18");
System.out.print(jsonObject);
}
It adds this property at the end of the document not as I expect under body.
jsonObject is the root node. You need to navigate to the node you want to modify.
JsonObject body = jsonObject.getAsJsonObject("body");
body.addProperty("AddANewFieldHere","2016-04-18");
From the example output, it looks like want it under the path body/search/searchId not body though:
JsonObject searchId = jsonObject
.getAsJsonObject("body")
.getAsJsonObject("search")
.getAsJsonObject("searchId");
searchId.addProperty("AddANewFieldHere","2016-04-18");

unable to parse a valid JSON String

I am trying to parse a JSON String and map it to a hashmap, I have a valid JSONString from server but when I traverse through it, all I can get it is the first result.
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String,String>>();
JSONObject jsonObj = new JSONObject(value);
Log.d("Jello",jsonObj.toString());
peoples = jsonObj.getJSONArray("product");//check here
Log.d("Jello",peoples.toString());
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
My JSON String is :
{"product":[{"sgroup":"Dummy_BIG_ONE","service":"Dummy_UNDER_BIG_ONE","code":"128","value":"0","updated_at":"2015-12-04 21:21:00"}]}{"product":[{"sgroup":"Hello Monkey","service":"Do u work","code":"123","value":"0","updated_at":"2015-12-04 21:27:51"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:39"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:40"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:42"}]}{"product":[{"sgroup":"Hello World","service":"Donkey","code":"24411","value":"0","updated_at":"2015-12-04 22:57:05"}]}{"product":[{"sgroup":"lkfnhjdiofho","service":"dfjdifj","code":"1101","value":"0","updated_at":"2015-12-05 01:15:49"}]}{"product":[{"sgroup":"Baal","service":"Saal","code":"1234","value":"21","updated_at":"2015-12-05 01:34:59"}]}{"product":[{"sgroup":"Inis","service":"Mona","code":"1234","value":"1001","updated_at":"2015-12-05 01:39:51"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:50:42"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:55:12"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"1000","updated_at":"2015-12-05 01:56:10"}]}
or HERE
here is how I am sending the JSON
while($row = mysql_fetch_assoc($output))
{
$product = array();
$product["sgroup"] = $row["service_group"];
$product["service"] = $row["service"];
$product["code"] = $row["code"];
$product["value"] = $row["amount"];
$product["updated_at"] = $row["updated_at"];
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
}
I want to add all the data's from the JSON in my ArrayList so that I can use it later.
Thank you for your help.
First, there are online tools available to determine if your JSON is valid.
Here is a general example of a better way to format your JSON data:
<?php
$bigArray = array();
for ($x = 0; $x <= 10; $x++) {
$product = array();
$product["sgroup"] = $x;
$product["service"] = $x;
$product["code"] = $x;
$product["value"] = $x;
$product["updated_at"] = $x;
array_push($bigArray, $product);
}
// echoing JSON response
echo json_encode($bigArray);
?>
Which gives this valid JSON response that is simple and easy to parse:
[
{
"sgroup":0,
"service":0,
"code":0,
"value":0,
"updated_at":0
},
{
"sgroup":1,
"service":1,
"code":1,
"value":1,
"updated_at":1
},
{
"sgroup":2,
"service":2,
"code":2,
"value":2,
"updated_at":2
},
{
"sgroup":3,
"service":3,
"code":3,
"value":3,
"updated_at":3
},
{
"sgroup":4,
"service":4,
"code":4,
"value":4,
"updated_at":4
},
{
"sgroup":5,
"service":5,
"code":5,
"value":5,
"updated_at":5
},
{
"sgroup":6,
"service":6,
"code":6,
"value":6,
"updated_at":6
},
{
"sgroup":7,
"service":7,
"code":7,
"value":7,
"updated_at":7
},
{
"sgroup":8,
"service":8,
"code":8,
"value":8,
"updated_at":8
},
{
"sgroup":9,
"service":9,
"code":9,
"value":9,
"updated_at":9
},
{
"sgroup":10,
"service":10,
"code":10,
"value":10,
"updated_at":10
}
]
As for the parsing, using a HashMap is not the best way. Create a list of Person POJO objects.
First define the Person class:
class Person {
public String group;
public String service;
public String value;
public String updated;
public Person(String g, String s, String v, String u) {
group = g;
service = s;
value = v;
updated = u;
}
}
Then, parsing is fairly simple:
List<Person> personList = new ArrayList<>();
JSONArray jsonArr;
try {
jsonArr = new JSONArray(response);
for(int i=0;i<jsonArr.length();i++){
JSONObject c = jsonArr.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
Person p = new Person(service_group, service, value, updated_at);
personList.add(p);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You should put your products into json array:
[
{
"product": {
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
}
},
{
"product": {
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
}
},
{
"product": {
"sgroup": "Inis",
"service": "Mona",
"code": "1234",
"value": "1001",
"updated_at": "2015-12-05 01:39:51"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:50:42"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:55:12"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "1000",
"updated_at": "2015-12-05 01:56:10"
}
}
]
And you have to change your parser little bit:
JSONArray jsonArray = new JSONArray(string);
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i).getJSONObject("product");
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
You don't need put your object into "product" attribute, but directly into array :
[
{
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
},
{
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
},

Categories