I have a JsonArray Object like
JsonArray[0]= { "streetName" : "xyz", "wardName" : "12xz"}
JsonArray[1]= { "doorNumber" : "123", "plot" : "90z"}
JsonArray[2]= { "city" : "pqr", "district" : "nmc"}
JsonArray[3]= { "state" : "hisd", "country" : "kasps"}
I want to convert above JsonArray into JsonObject which will be like
{
"addresss":[ {
"streetName": "xyz",
"wardName": "12xz",
"doorNumber": "123",
"plot": "90z",
"city": "pqr",
"district": "nmc",
"state": "hisd",
"country": "kasps"
}]
}
I tried in different ways using Json Objcet put and traversing JSONarray and appending the value to String builder. No use. any one give me some idea. how to do that. Thanks for your help.
Related
How i can parse json string like this:
{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
}
}
But, from "address" i need only "city". How i can make it without creating new class (for lib. GSON)?
I try use JsonPath, but i cant understand how replace JsonObject "address" to String value "city".
Here you go
try {
JSONObject jsonObject=new JSONObject(jsonString);
JSONObject address=jsonObject.getJSONObject("address");
String city=address.getString("city");
} catch (JSONException e) {
e.printStackTrace();
}
Try something like
DocumentContext ctx = JsonPath.parse("your-json-here");
YourPojoHere pojo = new YourPojoHere(
ctx.read("$.firstName"),
ctx.read("$.lastName"),
ctx.read("$.age"),
ctx.read("$.address.city"));
I suppose I understood your question correct: you want to replace /address with /address/city, so that
{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
}
}
would then be
{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : "Nara"
}
Option A: You could use it.bewares JSON, then using JSON Selectors it would be simply:
JSONFactory JSON = new JSONFactory(SimpleJSONParser.class, SimpleJSONGnerator.class);
String input = "{\"firstName\":\"John\",\"lastName\":\"doe\",\"age\":26,\"address\":{\"streetAddress\":\"naist street\",\"city\":\"Nara\",\"postalCode\":\"630-0192\"}}";
JSONValue json = JSON.parse(input);
json.put("address", JSON.find(new JSONSelector(".\"address\".\"city\"")))
You could use Dependecy Injection for the JSONFactory:
#Inject
JSONFactory JSON;
Option B: Instead you could use in combination with it.bewares JSON also it.bewares JSONPatch. JSON Patch is a proposed standard (see Wikipedia, RFC 6902)
A valid JSON Patch would be:
[
{ "op": "move", "from": "/address/city", "path": "/address" }
]
Using it.bewares JSONPatch it would be:
JSONFactory JSON = new JSONFactory(SimpleJSONParser.class, SimpleJSONGnerator.class);
String input = "{\"firstName\":\"John\",\"lastName\":\"doe\",\"age\":26,\"address\":{\"streetAddress\":\"naist street\",\"city\":\"Nara\",\"postalCode\":\"630-0192\"}}";
JSONValue json = JSON.parse(input);
String patchString = "[{\"op\":\"move\",\"from\":\"/address/city\",\"path\":\"/address\"}]";
JSONPatch patch = new JSONPatch(JSONArray<JSONObject<JSONString>> JSON.parse(patchString));
JSONPatch.execute(patch, json);
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
I have a json (result) like the below , i need the value of Key "extra", that is "contact office".
I tried the below code, but it did not work, can you help?
JSONArray jsonArray = new JSONArray(result.toString().trim());
JSONObject json = jsonArray.getJSONObject(0).getJSONObject("student").getJSONArray("department").getJSONObject(0).getJSONObject("classes");
String val=json.getString("extra");
// JSON Example
{
"student": [
{
"department" : [
{
"classes" : [
{
"grade" : "A",
"fine" : "No"
},
{
"grade" : "B",
"fine" : "Yes",
"extra" : "contact office"
},
{
"grade" : "C",
"fine" : "NA"
}
],
}
],
}
],
}
You mixed up JSONArray and JSONObject a few times, not sure exactly what I had to change but the following will work:
JSONObject jsonObject = new JSONObject(result.toString().trim());
JSONArray jsonArray = jsonObject
.getJSONArray("student").getJSONObject(0).getJSONArray("department").getJSONObject(0)
.getJSONArray("classes");
String val = jsonArray.getJSONObject(1).getString("extra");
Is this a full sample? If so it doesn't start out as an array. Student is and object not an array. If it is just a sample of one item in the array then you're okay.
The second thing I noticed is: getJSONObject("classes"). Classes is an array not an object, this won't work.
Would you like to consider using JsonPath. You could do something like this -
String[] extraValues = JsonPath.read(json, "$.student[0].department[0].classes[*].extra");
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)}
I was trying to find a way to convert the json array to json string.
http://jsonpath.com/
JSON
{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
},
"phoneNumbers": [
{
"type" : ["iPhone"],
"number": "0123-4567-8888"
},
{
"type" : ["home"],
"number": "0123-4567-8910"
}
]
}
Output
iphone
Expression I tried,
$.phoneNumbers[:1].type[,]
$.phoneNumbers[:1].type
$.phoneNumbers[:1].type
Thanks in advance