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"
}
Related
I have a json as below. I want to get mobile_number from this jsonObject.
json:-
{"id": "ABCD", "report": { "data": { "phone": { "mobile_number": 9876543210, "active": "Y", "content": null } } } }
I am doing it like this and it works fine but can someone help me with any other approach for it without getting every key.
JSONObject jsonObject = new JSONObject(json);
JSONObject report = getJSONObjectFromJson(jsonObject, "report");
JSONObject data = getJSONObjectFromJson(jsonObject, "data");
JSONObject phone = getJSONObjectFromJson(data, "phone");
long mobileNumber = getLongFromJson(phone, "mobile_number");
private Long getLongFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getLong(key) : null;
}
private JSONObject getJSONObjectFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getJSONObject(key) : null;
}
I've just dealing with the similar issue and decided to use JsonPath like this:
final DocumentContext jsonContext = JsonPath.parse(jsonString);
final Object read = jsonContext.read("$['report']['data']['phone']['mobile_number']");
You can use Jackson ObjectMapper.
try {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"id\": \"ABCD\", \"report\": { \"data\": { \"phone\": { \"mobile_number\": 9876543210, \"active\": \"Y\", \"content\": null } } } }";
JsonNode rootNode = mapper.readTree(jsonString);
JsonNode mobileNumber = rootNode.path("report").path("data").path("phone").path("mobile_number");
System.out.println("Mobile Number: " + mobileNumber.longValue());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
So there are lot of ways to do it but everything leads eventually to traversing the tree.
So to conclude all the approaches,
1. **Convert string to JsonObject and traverse.**
JSONObject jsonObject = new JSONObject(json);
JSONObject report = getJSONObjectFromJson(jsonObject, "report");
JSONObject data = getJSONObjectFromJson(jsonObject, "data");
JSONObject phone = getJSONObjectFromJson(data, "phone");
long mobileNumber = getLongFromJson(phone, "mobile_number");
private Long getLongFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getLong(key) : null;
}
private JSONObject getJSONObjectFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getJSONObject(key) : null;
}
2. **Using jackson objectMapper to get the JsonNode and then traverse.**
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode= mapper.readTree(json);
JsonNode mobileNumber = jsonNode.path("report").path("data").path("phone").path("mobile_number");
3. **Using gson jsonmapper to convert to map and then iterate the map.**
Gson gson = new Gson();
Map map = gson.fromJson(json, Map.class);
jsonObject.getJSONObject("x").getJSONObject("Y").getJSONObject("z");
Another route would be to leverage the ObjectMapper.
I have a json string returning:
[{"TRAIN_JOURNEY_STAFF[],"ID":15,"EMAIL_ADDRESS":"jk#connectedrail.com","PASSWORD":"test","FIRST_NAME":"Joe","LAST_NAME":"Kevin","DATE_OF_BIRTH":"1996-04-20T00:00:00","GENDER":"Male","STAFF_ROLE":"Conductor","PHOTO":null},{new record..}]
There are several records here, I can't find a way to convert this json string to individual objects. I'm using the following to read in the data:
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
}
I've tried the simple json libary but the parser mixes up the string, Which is not ideal as I need to output the data to rows object by object to jtables.
Any help would be appreciated.
Solved it with the below with GSON. Many thanks everyone!
JsonElement jelement = new JsonParser().parse(response.toString());
JsonArray jarray = jelement.getAsJsonArray();
JsonObject jobject = jarray.get(0).getAsJsonObject();
System.out.println(jobject.get("FIRST_NAME"));
You can use something like this:
public class ObjectSerializer {
private static ObjectMapper objectMapper;
#Autowired
public ObjectSerializer(ObjectMapper objectMapper) {
ObjectSerializer.objectMapper = objectMapper;
}
public static <T> T getObject(Object obj, Class<T> class1) {
String jsonObj = "";
T userDto = null;
try {
jsonObj = objectMapper.writeValueAsString(obj);
userDto = (T) objectMapper.readValue(jsonObj, class1);
System.out.println(jsonObj);
} catch (JsonProcessingException jpe) {
} catch (IOException e) {
e.printStackTrace();
}
return userDto;
}
Pass your JSON Object to this method alogn with class name and it will set the JSON data to that respective class.
Note:
Class must have the same variables as in the JSON that you want to map with it.
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
see this
You can use Jackson to convert JSON to an object.Include the dependency :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Then make a POJO class to store the JSON .The pojo class should reflect the json string structure and should have appropriate fields to map the values(Here in sample code Staff.class is a pojo class).Then, by using ObjectMapper class you can convert the JSON string to a java object as follows :
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(response.toString(), Staff.class);
Another simple method to read a JSON string and convert it into an object is :
JSON String:
{
"lastName":"Smith",
"address":{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":10021
},
"age":25,
"phoneNumbers":[
{
"type":"home", "number":"212 555-1234"
},
{
"type":"fax", "number":"212 555-1234"
}
],
"firstName":"John"
}
public class JSONReadExample
{
public static void main(String[] args) throws Exception
{
// parsing file "JSONExample.json"
Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
// typecasting obj to JSONObject
JSONObject jo = (JSONObject) obj;
// getting firstName and lastName
String firstName = (String) jo.get("firstName");
String lastName = (String) jo.get("lastName");
System.out.println(firstName);
System.out.println(lastName);
// getting age
long age = (long) jo.get("age");
System.out.println(age);
// getting address
Map address = ((Map)jo.get("address"));
// iterating address Map
Iterator<Map.Entry> itr1 = address.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
// getting phoneNumbers
JSONArray ja = (JSONArray) jo.get("phoneNumbers");
// iterating phoneNumbers
Iterator itr2 = ja.iterator();
while (itr2.hasNext())
{
itr1 = ((Map) itr2.next()).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
}
}
For reference:
https://www.geeksforgeeks.org/parse-json-java/
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
What you have basically is this :
[
{
"TRAIN_JOURNEY_STAFF":[
],
"ID":15,
"EMAIL_ADDRESS":"jk#connectedrail.com",
"PASSWORD":"test",
"FIRST_NAME":"Joe",
"LAST_NAME":"Kevin",
"DATE_OF_BIRTH":"1996-04-20T00:00:00",
"GENDER":"Male",
"STAFF_ROLE":"Conductor",
"PHOTO":null
},
{
}
]
You can use JSON constructor to serialize this array to an Array of JSONObjects.
Try looking for JSONObject and JSONArray classes in Java.
The constructor basically takes the stringified JSON (which you already have).
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());
}
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!
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);
}
}