Creating a JSON object - java

I am making a JSON request to server using Java. Here is the following parameters.
{method:'SearchBySearchConfiguration',params:[{{SearchCriteria:'%arriva',
IsAccountSearch:true,IsContactSearch:false,SearchByName:true,SearchByAddress:false
CRMTextValues:[], CRMCurrencyValues:[]}]}
I could do this way.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
How do I add the rest of params, in name-value pair to JSON object?
Thanks in advance!

One way I can think of is using the org.json library. I wrote a sample to build part of your request object:
public static void main(String[] args) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("method", "SearchBySearchConfiguration");
JSONArray jsonArray = new JSONArray();
JSONObject innerRecord = new JSONObject();
innerRecord.put("SearchCriteria", "%arriva");
innerRecord.put("IsAccountSearch", true);
jsonArray.put(innerRecord);
jsonObject.put("params",jsonArray);
System.out.println("jsonObject :"+jsonObject);
}
The output is :
jsonObject :{"method":"SearchBySearchConfiguration","params":[{"IsAccountSearch":true,"SearchCriteria":"%arriva"}]}
Another technique would be to build Java objects that resemble your request structure. You can then convert it into json using Jackson library's ObjectMapper class.
In both cases once you get the json string, you can directly write it into the request body.

JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
JSONArray paramsArr = new JSONArray();
JSONObject arrobj = new JSONOject();
arrobj.put("SearchCriteria","%arriva");
arrobj.put("IsAccountSearch","true");
arrobj.put("IsContactSearch","false");
arrobj.put("SearchByName","true");
arrobj.put("SearchByAddress","false");
arrobj.put("CRMTextValues",new JSONArray());
arrobj.put("CRMCurrencyValues",new JSONArray());
paramsArr.put(arrobj);
json.put("params",paramsArr);

The you can create JSONArray and put that array in JSONObject

Its Better to use gson for this.
First you need to create classs with following members :
public class TestClass{
private String method;
private ParamClass params;
}
public class ParamClass{
private String SearchCriteria;
private boolean IsAccountSearch;
private boolean IsContactSearch;
private boolean SearchByName;
private boolean SearchByAddress;
private String[] CRMTextValues;
private String[] CRMCurrencyValues;
}
Usage :
Serializing :
Gson gson = new Gson();
String jsonString = gson.toJson(testClassObject);
Deserializing :
Gson gson = new Gson();
TestClass testClassObject = gson.fromJson(jsonString , TestClass.class);

See this below example, where a JSONArray is returned and then how i am converting it in JSONObject form...
public JSONArray go() throws IOException, JSONException {
JSONArray json = readJsonFromUrl("http://www.xxxxxxxx.com/AppData.aspx");
return json;
}
JSONArray jarr;
for(int i=0 ; i<jarr.length() ; i++){
JSONObject jobj = jarr.getJSONObject(i);
String mainText = new String();
String provText = new String();
String couText = new String();
try{
mainText = jobj.getString("Overview");
System.out.println(mainText);
}catch(Exception ex){}
try{
JSONObject jProv = jobj.getJSONObject("Provider");
provText = jProv.getString("Name");
System.out.println(provText);
}catch(Exception ex){}
try{
JSONObject jCou = jobj.getJSONObject("Counterparty");
couText = jCou.getString("Value");
System.out.println(couText);
}catch(Exception ex){}
Jackson is a very efficient to do JSON Parsing
See this link:
http://jackson.codehaus.org/
Gson is provided by google which is also a good way to handle JSON.

To add params, JSONArray is used.
Inside params, we use JSONObject to add data such as SearchByAddress, IsAccountSearch ..etc.
Reference http://www.mkyong.com/java/json-simple-example-read-and-write-json/
package com.test.json;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("method", "SearchBySearchConfiguration");
JSONArray list = new JSONArray();
JSONObject innerObj = new JSONObject();
innerObj.put("SearchCriteria","%arriva" );
innerObj.put("IsAccountSearch",true);
innerObj.put("IsContactSearch",false);
innerObj.put("SearchByName",true);
innerObj.put("SearchByAddress",false);
innerObj.put("CRMTextValues",new JSONArray());
innerObj.put("CRMCurrencyValues",new JSONArray());
list.add(innerObj);
obj.put("params", list);
System.out.print(obj);
}
}

Related

How can I create a new element/node and then add a new key and value to it?

I have the following code:
import org.json.JSONObject;
import org.json.XML;
public class Xml2Json {
public static void main(String[] args) {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
jsonObject.getJSONObject("users").append("marks",23); }
}
it produces the output shown below:
{"users":{"report":{"sub":"eng","score":30},"marks":[23],"user":{"name":"test1"}}}
But I need to add a new element newUser to users and the marks should be inside the newUser, just like:
{"users":{"report":{"sub":"eng","score":30},"newUser":{"marks":{23}},"user":{"name":"test1"}}}
Could anyone help me?
Instead of your code use below mentioned code:
public static void main(String[] args) throws JSONException {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
Map<String, int[]> marks = new HashMap<>();
marks.put("marks", new int[]{23});
jsonObject.getJSONObject("users").put("newUser", marks);
System.out.println(jsonObject);
}
where line jsonObject.getJSONObject("users").put("newUser", marks); will add new key(newUser) with corresponding mapping marks as Map object.
Without Map and HashMap:
public static void main(String[] args) throws JSONException {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
JSONObject marksJSONObject = new JSONObject();
marksJSONObject.put("marks",new int[]{23});
jsonObject.getJSONObject("users").put("newUser", marksJSONObject);
System.out.println(jsonObject);
}
OUTPUT:
{"users":{"newUser":{"marks":[23]},"report":{"sub":"eng","score":30},"user":{"name":"test1"}}}
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
JSONObject newUser = new JSONObject();
newUser.put("marks", 32);
jsonObject.put("newUser", newUser);

Retrieving a single deep down array in JSON

So here is the JSON
{
"response": {
"data": {
"images": {
"image": [
{...
I want to access the image array. I was wondering if the following code was the best way to do it:
JSONObject jsonObjectResponse = new JSONObject(jsonString);
JSONObject jsonResponse = jsonObjectResponse.getJSONObject("response");
JSONObject jsonObjectData = new JSONObject(jsonResponse.toString());
JSONObject jsonData = jsonObjectData.getJSONObject("data");
JSONObject jsonObjectImages = new JSONObject(jsonData.toString());
JSONObject jsonImages = jsonObjectImages.getJSONObject("images");
JSONObject jsonObjectImage = new JSONObject(jsonImages.toString());
JSONArray jsonImageArray = jsonObjectImage.getJSONArray("image");
I feel like this requires a lot of time for a simple task. Does anyone have a more "engineered" solution?
Thanks a lot!
No, that's not the best way to do it. You keep converting from JSONObjects to Strings and then back to JSONObjects again. You should be able do:
JSONArray jsonImageArray = new JSONObject(jsonString)
.getJSONObject("response")
.getJSONObject("data")
.getJSONObject("images")
.getJSONArray("image");
Even if you just remove all of the toString calls, it becomes a lot more concise (but I would still favour the above example):
JSONObject jsonObjectResponse = new JSONObject(jsonString);
JSONObject jsonResponse = jsonObjectResponse.getJSONObject("response");
JSONObject jsonData = jsonResponse.getJSONObject("data");
JSONObject jsonImages = jsonData.getJSONObject("images");
JSONArray jsonImageArray = jsonImages.getJSONArray("image");
I think you can simply combine all these statements in the following way:
JSONObject jsonObjectResponse = new JSONObject(jsonString);
JSONArray jsonImageArray = jsonObjectResponse.getJsonObject("data")
.getJsonObject("images")
.getJsonArray("image");
Can you not chain the getJSONObject function?
JSONObject jsonObjectResponse = new JSONObject("jsonString");
JSONObject jsonImages = jsonObjectResponse.getJSONObject("response").getJSONObject("data")....
Try following:
JSONObject jsonObjectResponse = new JSONObject(jsonString);
JSONArray imageArray = jsonObjectResponse.getJSONObject("response")
.getJSONObject("data")
.getJSONObject("images")
.getJSONArray("image")
Hope it would work.
You can user chain calls:
String jsonString = "{\"response\":{\"data\":{\"images\":{\"image\":[]}}}}";
JSONObject json = new JSONObject(jsonString);
JSONArray image = json.getJSONObject("response")
.getJSONObject("data")
.getJSONObject("images")
.getJSONArray("image");
E.g. your image objects like {"title":"Some image","url":"http://..."}, so:
JSONObject firstImage = image.getJSONObject(0);
String url = firstImage.getString("url");
Or you can use GSON. Your classes:
class ServerAnswer {
private Response response;
// constructors, getters, setters
}
class Response {
private Data data;
// constructors, getters, setters
}
class Images {
#SerializedName("image")
private Image[] images;
// constructors, getters, setters
}
class Image {
private String url, title;
// constructors, getters, setters
}
And parse:
ServerAnswer answer = new Gson().fromJson(jsonString, ServerAnswer.class);
Image[] images = answer.getResponse().getData().getImages().getImagesArray();
Image firstImage = images[0];
String url = firstImage.getUrl();
In your case:
public class Images {
#SerializedName("image")
public ArrayList<String> image;
}
public class Data {
#SerializedName("images")
public Images images;
}
public class Response {
#SerializedName("data")
public Data data;
}
public class MyData {
#SerializedName("response")
public Response response;
}
then
MyData data = new Gson().fromJson(yourJsonString, MyData.class);
I think this is the best approach
You can try following code.
JSONArray jsonResponseArray = new JSONObject(strJson).getJSONObject("response").getJSONObject("data").getJSONObject("images").getJSONArray("image");
Hope this will help you.

JSONObject with List to String to JsonNode

I convert JSONObject in string for parse it in JsonNode with jackson but i have a List in my JSONObject and when i parse it with a ObjectMapper i get this :
["{Property1 : value1, Property2 : value2}"]
And i can't call myJsonNodeObject.get(i).get("Property1") this is my problem.
I have tried to cast my List in JSONArray in my JSONObject but don't work.
resultAsJSONObject = new JSONObject();
resultAsJSONObject.put("Label", getMetricStatisticsResult.getLabel());
resultAsJSONObject.put("Datapoints", getMetricStatisticsResult.getDatapoints());
resultAsJSONObject.put("fromDate", fromDate.getTimeInMillis());
resultAsJSONObject.put("toDate", toDate.getTimeInMillis());
resultAsJSONObject.put("error", "");
resultAsString = resultAsJSONObject.toString();
mapper.readValue(resultAsString, MetricsData.class);
Assuming that you have a JSON string which you just want to change. Then you can use Jackson to parse it as a ObjecNode and then modify it. Here is an example:
public class JacksonModifyJson {
static final String JSON = "{\"name\":\"Bob\", \"age\":13}";
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final ObjectNode jsonNode = mapper.readValue(JSON, ObjectNode.class);
jsonNode.put("url", "example.com");
System.out.println(mapper.writeValueAsString(jsonNode));
}
}
Output:
{"name":"Bob","age":13,"url":"example.com"}
THis method is really easy and works too
try {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}

Gson deserialize not working properly

I have a jsonarray formatted like this:
String jsonArray = {"myList":[{"code":"01","price":"2,3", "date":"21/12/2014"},{"code":"02","price":"3,4", "date":"26/12/2014"}]}
Mylist class is:
public class MyList {
private String code;
private String price;
private String date;
//..getter and setter
}
My non working "deserializator" is the following:
ObjectMapper objectMapper = new ObjectMapper();
List<MyList> list = new ObjectMapper().readValue(jsonArray, new TypeReference<List<MyList>>() { });
catching the following exception:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
How can I solve that?
Thanks in advance!
Here's my own working solution using Gson:
String jsonArray = {"myList":[{"code":"01","price":"2,3", "date":"21/12/2014"},{"code":"02","price":"3,4", "date":"26/12/2014"}]}
Gson gson = new Gson();
JsonParser parser = new JsonParser();
List<MyList> list = new ArrayList<MyList>();
try {
JsonArray jArray = (JsonArray) parser.parse(jsonArray).getAsJsonObject().get("myList");
for (JsonElement jObj : jArray) {
MyList item = gson.fromJson( jObj , MyList.class);
list.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope it will be useful for other users!

Java Append object to JSON

I would like to append JSON object to existing JSON array to get data structure like this.
"results":[
{
"lat":"value",
"lon":"value"
},
{
"lat":"value",
"lon":"value"
}
]
I'm trying to do it using the code in example, but unfortunately whole object is overriden everytime.
Log.i(AppHelper.APP_LOG_NAMESPACE, "POSITIONS AVAILABLE " + jsonDataString);
AppHelper helper = new AppHelper(ctx);
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
//putv given values to the JSON
valuesObject.put("lat", lat.toString());
valuesObject.put("lon", lon.toString());
valuesObject.put("city", city);
valuesObject.put("street", street);
valuesObject.put("date", helper.getActualDateTime());
valuesObject.put("time", helper.getActualDateTime());
list.put(valuesObject);
//mainObject.put("values", list);
mainObject.accumulate("values", list);
saveJsonData(ctx, mainObject.toString(),"positions");
How it should be right?
Put and accumulate everytime rewrite all previous values, but i would like to append this object:
{
"lat":"value",
"lon":"value"
},
Into results parent.
BTW: I would like to do it without GSON.
Thanks for any help..
There isnt any problem with your code. It does append
String jsonDataString = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("lat", "newValue");
valuesObject.put("lon", "newValue");
valuesObject.put("city", "newValue");
valuesObject.put("street", "newValue");
valuesObject.put("date", "newValue");
valuesObject.put("time", "newValue");
list.put(valuesObject);
mainObject.accumulate("values", list);
System.out.println(mainObject);
This prints {"values":[[{"date":"newValue","city":"newValue","street":"newValue","lon":"newValue","time":"newValue","lat":"newValue"}]],"results":[{"lon":"value","lat":"value"},{"lon":"value","lat":"value"}]}.
Isnt this what you are expecting?
With gson you can do like
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class AddJson {
public static void main(String[] args) {
String json = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
Gson gson = new Gson();
JsonObject inputObj = gson.fromJson(json, JsonObject.class);
JsonObject newObject = new JsonObject() ;
newObject.addProperty("lat", "newValue");
newObject.addProperty("lon", "newValue");
inputObj.get("results").getAsJsonArray().add(newObject);
System.out.println(inputObj);
}
}
Simple Approach
String jsonData = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }]}";
System.out.println(jsonData);
try {
JSONArray result = new JSONObject(jsonData).getJSONArray("results");
result.getJSONObject(0).put("city","Singapore");
jsonData = "{\"results\":"+result.toString()+"}";
System.out.println(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
OutPut Before Appending
{"results":[{"lat":"value","lon":"value" }]}
OutPut After Appending
{"results":[{"lon":"value","lat":"value","city":"Singapore"}]}
If you want to add new value to an Object you can try the below as well
Before:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty"
}
code :
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(TheObjectToWhichYouWantToAddNewValue);
ObjectNode node = (ObjectNode) mapper.readTree(json);
node.putPOJO("new Key","new value")
after:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty",
"new Key": "new value"
}

Categories

Resources