append json object to existing array of json object - java

I am trying to append new json object in existing json array of object. I am new in json. so please help me.
existing json :
{
"cluster":[
{
"path":"home/Nik",
"password":"welcome",
"isQueen":"true",
"host":"192.168.11.248",
"isQueenWorker":"true",
"user":"Nik"
}
]
}
new json :
{
"path":"home\/Nik",
"password":"welcome",
"isQueen":"true",
"host":"192.168.11.248",
"isQueenWorker":"true",
"user":"Nik"
}
I want to add new json to existing json array.

You may use it like below, you need to use push command to push an object inside an array.
var myObj = {
"cluster":[
{
"path":"home/Nik",
"password":"welcome",
"isQueen":"true",
"host":"192.168.11.248",
"isQueenWorker":"true",
"user":"Nik"
}
]
};
var x = {
"path":"home\/Nik",
"password":"welcome",
"isQueen":"true",
"host":"192.168.11.248",
"isQueenWorker":"true",
"user":"Nik"
};
alert(JSON.stringify(myObj))
var newArr = myObj.cluster;
newArr.push(x) //pushing object x in newArr. similarly you can add multiple objects in to it
var myJSON = JSON.stringify(newArr);
alert(myJSON)

you can directly append it
eg. first json
{"cluster":[{"path":"home/Nik","password":"welcome","isQueen":"true","host":"192.168.11.248","isQueenWorker":"true","user":"Nik"}]}
int i= cluster.length();
cluster[i]={"path":"home/Nik","password":"welcome","isQueen":"true","host":"192.168.11.248","isQueenWorker":"true","user":"Nik"}

Related

Simplest way to convert this array in to the specified one using Java

I have this String Json Payload
[
"key1":{
"atr1":"key1",
"atr2":"value1",
"atr3":"value2",
"atr4":"value3,
"atr5":"value4"
},
"key2":{
"atr1":"key2",
"atr2":"value5",
"atr3":"value6",
"atr4":value7,
"atr5":"value8"
}
]
and I want it to be converted in to the following format using Java
[
{
"atr2":"value1",
"atr3":"value2",
"atr4":"value3,
"atr5":"value4"
},
{
"atr2":"value5",
"atr3":"value6",
"atr4": "value7",
"atr5":"value8"
}
]
What would be the simplest way of transforming this ?
You cannot, because the example below is not valid json.
Check it out using this JSON validator.
If you paste this in (I've fixed some basic errors with lack of quotes)
{
{
"atr2":"value1",
"atr3":"value2",
"atr4":"value3",
"atr5":"value4"
},
{
"atr2":"value5",
"atr3":"value6",
"atr4":"value7",
"atr5":"value8"
}
}
You will get these errors ...
It can work if you change the target schema to something like this by using a json-array to contain your data.
[
{
"atr2":"value1",
"atr3":"value2",
"atr4":"value3",
"atr5":"value4"
},
{
"atr2":"value5",
"atr3":"value6",
"atr4":"value7",
"atr5":"value8"
}
]
If this works for you, then this problem can easily be solved by using the ObjectMapper class.
You use it to deserealize the original JSON into a class, which has two fields "key1" and "key2"
Extract the values of these fields and then just store them in an array ...
Serialize the array using the ObjectMapper.
Here a link, which explains how to use the ObjectMapper class to achieve the goals above.
EDIT:
So you'll need the following classes to solve the problem ...
Stores the object data
class MyClass {
String atr2;
String art3;
}
Then you have a container class, which is used to store the initial json.
class MyClassContainer {
MyClass key1;
MyClass key2;
}
Here's how you do the parse from the original json to MyClassContainer
var mapper = new ObjectMapper()
var json = //Get the json String somehow
var myClassContainer = mapper.readValue(json,MyClassContainer.class)
var mc1 = myClassContainer.getKey1();
var mc2 = myClassContainer.getKey2();
var myArray = {key1, key2}
var resultJson = mapper.writeValueAsString(myArray)
Assuming that you will correct the JSON into a valid one (which involves replacing the surrounding square braces with curly ones, and correct enclosure of attribute values within quotes), here's a simpler way which involves only a few lines of core logic.
try{
ObjectMapper mapper = new ObjectMapper();
mapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
HashMap<String, Data> map = mapper.readValue( jsonString, new TypeReference<HashMap<String, Data>>(){} );
String json = mapper.writeValueAsString( map.values() );
System.out.println( json );
}
catch( JsonProcessingException e ){
e.printStackTrace();
}
jsonString above is your original JSON corrected and valid JSON input.
Also notice the setting of FAIL_ON_UNKNOWN_PROPERTIES to false to allow atr1 to be ignored while deserializing into Data.
Since we are completely throwing away attr1 and its value, the Data class will represent all fields apart from that.
private static class Data{
private String atr2;
private String atr3;
private String atr4;
private String atr5;
}

Json strings to Json array

Good day!
I have an array of json objects like this :
[{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
},
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}]
For some reasons I need to split then to each element and save to storage. In the end I have many objects like
{ "senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
}
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}
After some time I need to combine some of them back into json array.
As I can see - I can get objects from storage, convert them with Gson to objects, out objects to a list, like this:
String first = "..."; //{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":0}
String second = "...";//{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":4}
BaseMessage msg1 = new Gson().fromJson(first, BaseMessage.class);
BaseMessage msg2 = new Gson().fromJson(second, BaseMessage.class);
List<BaseMessage> bmlist = new ArrayList<>();
bmlist.add(msg1);
bmlist.add(msg2);
//and then Serialize to json
But I guess this is not the best way. Is there any way to combine many json-strings to json array? I rtyed to do this:
JsonElement elementTm = new JsonPrimitive(first);
JsonElement elementAck = new JsonPrimitive(second);
JsonArray arr = new JsonArray();
arr.add(elementAck);
arr.add(elementTm);
But JsonArray gives me escaped string with json - like this -
["{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":4
}","
{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":0
}"]
How can I do this?
Thank you.
At the risk of making things too simple:
String first = "...";
String second = "...";
String result = "[" + String.join(",", first, second) + "]";
Saves you a deserialization/serialization cycle.

Inserting JSON Subobject into existing JSON

I get JSON back from a web service call that looks like this:
{
results :
{
seg: {
segName: whatever,
segType: atest,
var: [
{field1: value1,
field2: value2,
field3: value3},
{field1: value4,
field2: value5,
field3: value6}
]
}
}
}
I am using the net.sf.json package in Java. I create a JSON object from this result.
I would like to manually add another entry (JSONObject) to the array "var".
Other than deconstructing the object all the way down to the JSONArray "var", and then rebuilding it, is there a way to just insert another entry into var?
I tried accumulate("var", new JSONObject(...)); but that stuck the new object at the same level as "seg" in the "results" section.
You have to call accumulate at the level you want the new object inserted.
If you drill down to the "seg" level, and accumulate the new object there, you'll add the new entry to the "var" array.
e.g.
String json = // your input JSON string here
JSONObject obj = new JSONObject(json);
obj.getJSONObject("results")
.getJSONObject("seg")
.accumulate("var", new JSONObject("{field1 : value7, field2: value8, field3: value9}"));
System.out.println(obj);
gives
{"results":{"seg":{"var":[{"field3":"value3","field2":"value2","field1":"value1"},{"field3":"value6","field2":"value5","field1":"value4"},{"field3":"value9","field2":"value8","field1":"value7"}],"segType":"atest","segName":"whatever"}}}

Java - Retrieving nested JSON array key values

I've got a JSON response that looks like this:
USER:[{
"id":"145454",
"name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true,
"caregiverName":"Jones"
}]
I'm trying to create a java method so I can access the key value pairs of the nested JSONArray. For example I don't want the entire JSON array I just want to retrieve the doctor name from the patientInfo JSON array. Any ideas how I would do this in Java I'm completely stuck here.
This is sudo code but I imagine it would be something like:
String doctorInfo() {
JSONObject obj = new JSONObject(user)
JSONArray arr = obj.getJSONArray("patientInfo")
String doctor = arr.getValue("doctor")
}
And I'd like to be able to access it on the front end by doing
doctorInfo().doctor
Code samples are greatly appreciated.
The code will be like this:
String doctorInfo(String jsonString) {
JSONObject obj = new JSONObject(jsonString)
JSONArray arr = obj.getJSONArray("patientInfo")
JSONObject patientJSONObject = arr.getJSONObject(0);
String doctor = patientJSONObject.getString("doctor");
return doctor;
}
The above code sample assumes you are passing the below string as the parameter.
{ "id":"145454", "name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true, "caregiverName":"Jones" }

How to properly format JSON string in java?

I have a jersey client that is getting JSON from a source that I need to get into properly formatted JSON:
My JSON String looks like the folllowing when grabbing it via http request:
{
"properties": [
{
someproperty: "aproperty",
set of data: {
keyA: "SomeValueA",
keyB: "SomeValueB",
keyC: "SomeValueC"
}
}
]
}
I am having problems because the json has to be properly formatted and keyA, keB, and keyC are not surrounded in quotes. Is there some library that helps add quotes or some best way to go about turning this string to properly formatted json? Or if there is some easy way to convert this to a json object without writing a bunch of classes with variables and lists that match the incoming structure?
you can use json-lib. it's very convenient! you can construct your json string like this:
JSONObject dataSet = new JSONObject();
dataSet.put("keyA", "SomeValueA") ;
dataSet.put("keyB", "SomeValueB") ;
dataSet.put("keyC", "SomeValueC") ;
JSONObject someProperty = new JSONObject();
dataSet.put("someproperty", "aproperty") ;
JSONArray properties = new JSONArray();
properties.add(dataSet);
properties.add(someProperty);
and of course you can get your JSON String simply by calling properties.toString()
I like Flexjson, and using lots of initilizers:
public static void main(String[] args) {
Map<String, Object> object = new HashMap<String, Object>() {
{
put("properties", new Object[] { new HashMap<String, Object>() {
{
put("someproperty", "aproperty");
put("set of dada", new HashMap<String, Object>() {
{
put("keyA", "SomeValueA");
put("keyB", "SomeValueB");
put("keyC", "SomeValueC");
}
});
}
} });
}
};
JSONSerializer json = new JSONSerializer();
json.prettyPrint(true);
System.out.println(json.deepSerialize(object));
}
results in:
{
"properties": [
{
"someproperty": "aproperty",
"set of dada": {
"keyA": "SomeValueA",
"keyB": "SomeValueB",
"keyC": "SomeValueC"
}
}
]
}
Your string isn't JSON. It's something that bears a resemblance to JSON. There is no form of JSON that makes those quotes optional. AFAIK, there is no library that will reads your string and cope with the missing quotes and then spit it back out correctly. You need to find the code that produced this and repair it to produce actual JSON.
You can use argo, a simple JSON parser and generator in Java

Categories