org.json.simple. add header node - java

I'm using org.json.simple library and I have a json which looks like below
[
{
"lastName": "abc",
"firstName": "def",
"email": "abc#test.com",
},
{
"lastName": "xyz",
"firstName": "pqr",
"email": "xyz#test.com",
}
]
I need to add a header node. for example .. it should look like below. How to add "users" ??
{
"users" :
[
{
"lastName": "abc",
"firstName": "def",
"email": "abc#test.com",
},
{
"lastName": "xyz",
"firstName": "pqr",
"email": "xyz#test.com",
}
]
}
I already have org.json.simple.JSONObject for the above json..now I just need to add "users" at the top of json.

Put you existing array in to a new object.
JSONParser parser = new JSONParser();
JSONArray arr = (JSONArray) parser.parse("[{\"lastName\": \"abc\", \"firstName\": \"def\", \"email\": \"abc#test.com\" }, { \"lastName\": \"xyz\", \"firstName\": \"pqr\", \"email\": \"xyz#test.com\" }]");
System.out.println(arr); // First Json object (arr)
JSONObject obj = new JSONObject();
obj.put("users", arr);
System.out.println(obj); // Second Json object

Related

Json comparison which contains arrays using Java

Json1:
{
"array1": [
{
"Name": "Xytrex Co.",
"Description": "Industrial Cleaning Supply Company",
"Account Number": "ABC15797531",
"Address": {
"Street": "st.road",
"pin": "789723"
}
},
{
"Name": "XYZ Company",
"Address": {
"Street": "Peters road",
"pin": "789700"
}
}
]
}
Json2:
{
"array2":[
{
"Name": "Xytrex Co.",
"Description": "Industrial Cleaning Supply Company",
"Account Number": "ABC15797531",
"Address": {
"Street": "st.road",
"pin": "789723"
}
},
{
"Name": "XYZ Company",
"Description": "Domestic Cleaning Supply Company",
"Address": {
"Street": "Peters road",
"pin": "789700"
}
}
]
}
Java Code used by me:
JsonParser Parser = new JsonParser();
Object obj1 = Parser.parse(new
FileReader("/home/cloudera/Desktop/SampleJson/src/JSON1.json"));
Object obj2 = Parser.parse(new
FileReader("/home/cloudera/Desktop/SampleJson/src/JSON2.json"));
JsonObject jsonObject1 = (JsonObject) obj1;
JsonObject jsonObject2 = (JsonObject) obj2;
Set<Map.Entry<String, JsonElement>> entries1 = jsonObject1.entrySet();
Set<Map.Entry<String, JsonElement>> entries2 = jsonObject2.entrySet();
for (Map.Entry<String, JsonElement> entry : entries1) {
//System.out.println("FirstJson:"+entry.getKey());
}
for (Map.Entry<String, JsonElement> entry : entries2) {
//System.out.println("SecondJson:"+entry.getKey());
}
if (jsonObject1.equals(jsonObject2)) {
System.out.println("Success");
} else {
entries1.removeAll(entries2);
//System.out.println("\n");
System.out.println("Result:" + entries1);
}
I have to compare two json files which contain arrays using Java, In array1 "Description" is missing I have to print that exact key and not the entire Json from first to last. In my output also "Description" is not there, but it's not printing exactly that key, its printing from first to last. Please help me with this.
The output I got:
Result:[array1=[{"Name":"Xytrex Co.","Description":"Industrial Cleaning Supply Company","Account Number":"ABC15797531","Address":{"Street":"st.road","pin":"789723"}},{"Name":"XYZ Company","Address":{"Street":"Peters road","pin":"789700"}}]]
This library is clean way to handle json comparison. It also has compare mode like strict check etc.
http://jsonassert.skyscreamer.org/javadoc/org/skyscreamer/jsonassert/JSONCompare.html
For your usecase you can check JSONCompareResult solves your problem.
I'd suggest you to use https://github.com/eBay/json-comparison library.
This library based on JsonAssert project but provide additional features
such as 'Exclude paths' , dealing with order and more

Parsing JSON when nested or otherwise a bit more complicated than single values [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
Here's the JSON:
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "123 Main street",
"city": "Anytown",
"postalCode": "12345"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "123-456-8888"
},
{
"type": "home",
"number": "123-557-8910"
}
]
}
The question is, in Java, how do you access the address fields? I tried things like address.city, but that didn't work:
String city = (String) jsonObject.get("address.streetAddress");
System.out.println(city);
Would appreciate any suggestions.
You need to call getString on the address object that you get.
String city = jsonObject.getJSONObject("address").getString("streetAddress");
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "123 Main street",
"city": "Anytown",
"postalCode": "12345"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "123-456-8888"
},
{
"type": "home",
"number": "123-557-8910"
}
]
}
first get your address.Address is an object.{} means object,[] means an array.
JSONObject addressObj = jsonObject.get("address");
now you have a reference to the address.
String addressStr = addressObj.get("streetAddress");
String cityStr = addressObj.get("city");
int cityInt = Integer.parseInt(addressObj.get("postalCode"));
If i don't wrong remember there should be getString("streetAddress") and getInteger("postalCode") to avoid parse issues.
Apart from the given answers you should add a check to see if the address is not blank before checking city or else you will end up getting and exception.
Here is updated example:
if( jsonObject.has("address"){
JSONObject addressObj = jsonObject.get("address");
if( addressObj.has("city"){
String cityStr = addressObj.get("city");
}
}

Not getting JSON data in the order in which i have entered

I am fetching details from a database table which contains 3 rows in JAVA.
I am using JSONarray and JSONObject as follows
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
JSONArray ja=new JSONArray();
The data from table is put to the jsonObject as follows for each one:
String qry="select * from details";
ResultSet res = select .executeQuery(qry);
while(res.next){
String Name=res.getString("name");
String age=res.getString("age");
.
.
jsonObject.put("Name", Name);
jsonObject.put("age", age);
.
.
ja.put(jsonObject);
}
mainjsonObject.put("PERSONAL DETAILS",ja);
I should get the output json as follows(i.e. the order in which i entered):
{
"PERSONAL DETAILS": [
{
" name": "abc",
"age": "4",
"gender": "F",
"Place": "abc1"
},
{
" name": "xyz",
"age": "3",
"gender": "M",
"Place": "abc2"
}
]
}
But am getting the values in random order like below:
{
"PERSONAL DETAILS": [
{
"age": "4",
" name": "abc",
"Place": "abc1"
"gender": "F",
},
{
"age": "3",
" name": "xyz",
"Place": "abc2"
"gender": "M",
}
]
}
Please help me with a solution. I need to get all the values in the same order in which i have entered.
You can try something like this to build json object construct using LinkedHashMap and then pass it to the constructor like this ,
LinkedHashMap<String, String> jsonOrderedMap = new LinkedHashMap<String, String>();
jsonOrderedMap.put("Name", res.getString(1));
...
...
// struct you want
JSONObject JSONorder = new JSONObject(jsonOrderedMap);
JSONArray sortedJSON = new JSONArray(Arrays.asList(JSONorder));

JSON to JSON Transform of input sample using any existing java library/tools

Input:
{
"Student": {
"name" :"abc",
"id" : 588,
"class : "12"
}
}
Reqired Output:
{
"Student": {
"key" :"name",
"value":"abc",
"key" :"id",
"value":"588",
"key" :"class",
"value":"12"
}
}
Your output json invalid. Json object can not duplicate key .
You can use the library org.json and do something like this:
JSONObject jsonObject = new JSONObject(inputJson);
JSONObject outputJson = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : jsonObject.keySet()) {
JSONObject item = new JSONObject();
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
item.put(keyStr, keyvalue);
array.put(item);
}
outputJson.put("Student", array);
System.out.println(json.toString());
Output :
{
"Student": [
{
"key": "name",
"value": "abc"
},
{
"key": "id",
"value": "588"
},
{
"key": "class",
"value": "12"
}
]
}
Similar to the other answer, the desired output JSON format is not valid.
The closest valid output would be
{
"Student" : [ {
"key" : "name",
"value" : "abc"
}, {
"key" : "id",
"value" : 588
}, {
"key" : "class",
"value" : "12"
} ]
}
This can be generated via Jolt with the following spec
[
{
"operation": "shift",
"spec": {
"Student": {
"name": {
"$": "Student[0].key",
"#": "Student[0].value"
},
"id": {
"$": "Student[1].key",
"#": "Student[1].value"
},
"class": {
"$": "Student[2].key",
"#": "Student[2].value"
}
}
}
}
]
This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.
The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:
{"Student" : array(.Student)}

Problems parsing JSON in Java

I have this json:
[{
"name": "prog 1",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}, {
"name": "prog 2",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}]
Now trying to parse it in Java like:
JSONObject json=new JSONObject(json_str);
throws an Exception, since it doesn't begin with {, but [ since it's an array. I can parse this without problem in js, but aparently I cannot load an JSONArray with this string...
use: JSONArray objArray = new JSONArray (json_str);
// to access the individual objects inside the array:
for(int i=0;i<objArray.length();i++)
{
JSONObject obj = objArray.getJSONObject(i);
}
Have you tried this:
JSONArray arr = new JSONArray(stringWithContent);
Then access it like :
for(int i = 0; i<arr.length();i++){
System.out.println(arr.get(i));
}
You can try following code
JSONObject jObject = new JSONObject(json_str);
JSONArray array = jObject.getJSONArray("show");
for(int i = 0 ; i < array.length() ; i++)
{
System.out.println(array.getJSONObject(i).getString("name"));
System.out.println(array.getJSONObject(i).getString("time"));
}
It will helpful ...

Categories