Extract json subset with few attributes from the main json - java

Is there an API/tool available for extracting specific attributes(json subset) of a json in java, similar to apache-commons beanutils copy?
For example I have the following JSON
{
"fixed":[
{
"b":"some value",
"c":"some value",
"d":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"c":"value",
"d":"value",
"e":"value",
"f":"value"
}
]
}
I would like to have the following json
{
"fixed":[
{
"b":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"e":"value",
"f":"value"
}
]
}
I came up the following method, but not sure if its the right approach
public JSONObject parseJSON(JSONObject data,List<String> subset){
JSONArray fixedArray = (JSONArray) data.get("fixed");
JSONObject resObj = new JSONObject();
JSONArray resArray = new JSONArray();
for(int i=0;i<fixedArray.size();i++){
JSONObject element = (JSONObject) fixedArray.get(i);
JSONObject resElement = new JSONObject();
for(String s:subset){
resElement.put(s, element.get(s));
}
resArray.add(resElement);
}
return resObj.put("fixed", resArray);
}
I had a look at this SO question, but wasn't helpful for this topic.

https://docs.oracle.com/javase/tutorial/jaxb/intro/arch.html you can also create you own pojo class from JAXB ,if you want.

Related

Parse the JSON response

i am trying to phrase the below json response and the get the "message" and "WORKORDERID" data in java
{
"operation": {
"result": {
"message": " successfully.",
"status": "Success"
},
"Details": {
"SUBJECT": "qqq",
"WORKORDERID": "800841"
}
}
}
Below is my code
JSONObject inputs = new JSONObject(jsonResponse);
JSONObject jsonobject = (JSONObject) inputs.get("operation");
String s = jsonobject.getString("message");
system.out.println("s");
Your objects are nested 2 times, therefore you should do:
JSONObject inputs = new JSONObject(jsonResponse);
JSONObject operation= (JSONObject) inputs.get("operation");
JSONObject result= (JSONObject) operation.get("result");
JSONObject details= (JSONObject) operation.get("Details");
String message = result.getString("message");
String workerId = details.getString("WORKORDERID");
JSONObject is somethink like Map-Wrapper, so you can think, that your JSON data-structure is Map<Map<Map<String, Object>, Object>, Object>. So, firstly you need to access to datas by first key (operation), secondly (result) and after that, you can access to desired field (message).
Note, that value of Map is Object, so you will need to cast your type to JSONObject.
sometimes JSONObject class is not found in java. so you will need to add jar
try{
// build the json object as follows
JSONObject jo = new JSONObject(jsonString);
// get operation as json object
JSONObject operation= (JSONObject) jo.get("operation");
// get result as json object
JSONObject result= (JSONObject) jo.get("result");
JSONObject details= (JSONObject) jo.get("Details");
// get string from the json object
String message = jo.getString("message");
String workerId = jo.getString("WORKORDERID");
}catch(JSONException e){
System.out.println(e.getMessage());
}

Adding json array in a json object in java

I am struggling to fit in a jsonArray inside a json object (through java code).. please help me out.
My Input JsonObject is :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W"
}
}
I will have to read "imageURL" property from this JSONObject and append its variants to the same json object (image variants will be in SortedSet data structure).
Sample O/P 1 :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
"http:example.com/imageResource_variant1.jpg",
"http:example.com/imageResource_variant2.jpg"
]
}
}
Sample O/P 2 :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
{
"url" : "http:example.com/imageResource_variant1.jpg"
},
{
"url" : "http:example.com/imageResource_variant2.jpg"
}
]
}
}
The logic i tried to get sample output 2 is some what like below,
// productDetail is the give input JSONObject
JSONObject product = productDetail.optJSONObject("products");
SortedSet<String> imageUrls = new TreeSet<>();
imageUrls.add("http:example.com/imageResource_variant1.jpg");
imageUrls.add("http:example.com/imageResource_variant2.jpg");
Iterator<String> itr = imageUrls.iterator();
JSONArray imageUrlsArray = new JSONArray();
while (itr.hasNext()) {
JSONObject imageUrlObj = new JSONObject();
imageUrlObj.put("url", itr.next());
imageUrlsArray.put(imageUrlObj);
}
product.append("variants", imageUrlsArray);
When i tried to print the productDetail JSON object after executing above logic
System.out.println(productDetail.toString());
I observed the following output :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
[
{
"url" : "http:example.com/imageResource_variant1.jpg"
},
{
"url" : "http:example.com/imageResource_variant2.jpg"
}
]
]
}
}
If you notice, It's coming up like Array of arrays (extra [ ] for "variants"),
Please help me in understanding Where my logic is going wrong.
And also, Please help me getting the First sample out put.
Appreciate quick response..
Thanks,
Rohit.
First sample can be archivable as simple as this:
JSONObject product = productDetail.optJSONObject("products");
JSONArray imageUrlsArray = new JSONArray();
imageUrlsArray.put(0, "http:example.com/imageResource_variant1.jpg");
imageUrlsArray.put(1, "http:example.com/imageResource_variant2.jpg");
product.append("variants", imageUrlsArray);
Try using put instead of append:
JSONObject product = productDetail.optJSONObject("products");
SortedSet<String> imageUrls = new TreeSet<>();
imageUrls.add("http:example.com/imageResource_variant1.jpg");
imageUrls.add("http:example.com/imageResource_variant2.jpg");
Iterator<String> itr = imageUrls.iterator();
JSONArray imageUrlsArray = new JSONArray();
while (itr.hasNext()) {
JSONObject imageUrlObj = new JSONObject();
imageUrlObj.put("url", itr.next());
imageUrlsArray.put(imageUrlObj);
}
-product.append("variants", imageUrlsArray);
+product.put("variants", imageUrlsArray);
From the docs:
Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated with a JSONArray, then the value parameter is appended to it.

extract from JSON

"biodata": {
"Ruby": {
"Expertise": "web development",
"EXperience": "5 years"
},
"Dylon": {
"Expertise": "Java",
"EXperience": "2 years"
}
}
I have the above JSONObject . I am trying to fetch some keys here .
I am looking to fetch the name key i.e Ruby , Dylon etc .
I am then trying to fetch the "Experience " key value .
Desired output :
name= Ruby
Experience = 5 years
My code :
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("path to JSON file"));
JSONObject jsonobj = (JSONObject) obj;
String statistics = jsonobj.getString("biodata"); //The method getString(String) is undefined for the type JSONObject
for (Iterator key = jsonobj.keys(); itr.hasNext();) {//The method keys() is undefined for the type JSONObject //itr cannot be resolved
JSONObject name = jsonobj.get(key.next()); //Type mismatch: cannot convert from Object to JSONObject
String key = key.next();//The method next() is undefined for the type String
JSONObject name = jsonobj.get(key); //Type mismatch: cannot convert from Object to JSONObject
Log.d("data", "key="+key+ " and value="+jsonobj.toString()); //Log cannot be resolved
}
I have mentioned the errors in the comment of my code .
You json is not valid .
You should change to this .
{
"biodata": {
"Ruby": {
"Expertise": "web development",
"EXperience": "5 years"
},
"Dylon": {
"Expertise": "Java",
"EXperience": "2 years"
}
}
}
Try this .
private void jsonParse() {
try {
// use jsonobject to parse json with
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("path to JSON file"));
JSONObject jsonObject = (JSONObject) obj;
// get jsonobject by biodata tag
JSONObject biodata = jsonObject.getJSONObject("biodata");
// use Iterator to get name
Iterator<String> names = biodata.keys();
// use while loop
while (names.hasNext()) {
// get name
String name = names.next().toString();
Log.d("data", "name=" + name);
// get jsonobject by name tag
JSONObject nameJsonObject = biodata.getJSONObject(name);
// get string
String Expertise = nameJsonObject.getString("Expertise");
String EXperience = nameJsonObject.getString("EXperience");
Log.d("data", "Experience =" + EXperience);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You have many issues in your code.
First: Assuming you want to implement code based on your current JSON String
Issues:
JSONObject API do not facilitate the methods of Map used in your implementation.
Your JSON String is not a array so for loop is not going to help, instead you should fetch the inner JSONObjects using the getJSONObject () method of the JSONObject API.
Casting the parsed object from your parser API will not automatically make it a JSONObject, the right way of doing this as below:
JsonObject jsonObject = parser.parse(new FileReader("path to JSON file")).getAsJsonObject();
Second: Assuming you intent to implement the JSON string representation as array, you should correct your JSON string as below.
"biodata": [{ "Ruby": { "Expertise": "web development", "EXperience": "5 years" }}, {"Dylon": { "Expertise": "Java", "EXperience": "2 years" } }]
With the above JSON string you can implement the fetching of data logic using JSONArray API

Java JsonObject from JsonArray

I have Json stored in javax.json.JsonObject, the object look like this:
{
"status":"ok",
"meta":{
"count":2
},
"data":{
"1":{
"id":40,
},
"17":{
"id":48,
}
}
}
How do I access the id key in the sub-object "1" ?
I tried:
obj.getJsonArray("data").getJsonArray("1").getJsonNumber("id").intValue();
However it does not work because the firt call of getJsonArray() method returns a JsonValue object not a JsonObject so the next call of getJsonArray fails. Any ideas ?
You can use an iterator approach to iterate thru the JSONObject:
JSONObject json = new JSONObject(input);
JSONObject jsonData = json.getJSONObject("data");
Iterator<?> jsonDataKeys = jsonData.keys();
while (jsonDataKeys.hasNext()) {
String key = (String)jsonDataKeys.next();
if (jsonData.get(key) instanceof JSONObject) {
System.out.println(((JSONObject) jsonData.get(key)).getInt("id"));
}
}
int id = obj.getJsonObject("data")
.getJsonObject("1")
.getInt("id");
JSONObject jObject = null;
jObject = new JSONObject(String you want to parse);
JSONObject j1Object = jObject.getJSONObject("data");
JSONObject j2Object = j1Object.getJSONObject("1");
String s1=j2Object.getString("id");
System.out.println(s1);

add array to json file with no key

I have to make a file in JSON format which must look like the following:
xyz.json
[
{
"imagelist": "/oracle/public/oel6",
"label": "test_higgs",
"shape": "small",
"name" : "/Compute-computecli1/computeadmin/",
"networking" : {
"eth0" : {
"ipnetwork" : "/Compute-computecli1/computeadmin/ipnet"
}
}
}
]
The array should be added in the JSON file without {}, and these curly brackets have to come inside the JSON array.
The code for
{
instances:[
{
"imagelist": "/oracle/public/oel6",
"label": "test_higgs",
"shape": "small",
"name" : "/Compute-computecli1/computeadmin/",
"networking" : {
"eth0" : {
"ipnetwork" : "/Compute-computecli1/computeadmin/ipnet"
}
}
}
]
}
is:
This code adds json array as a value to "instance" key, but I want to add json array without json key.
JsonObject ipnetwork = new JsonObject();
ipnetwork.addProperty("ipnetwork", ipNetworkName);
JsonObject interface_type = new JsonObject();
interface_type.add("eth0", ipnetwork);
JsonObject instance = new JsonObject();
instance.addProperty(imageListCmdText, "/oracle/public/oel6");
instance.addProperty("label","test_higgs");
instance.addProperty("shape","small");
instance.addProperty("name","/"+customerName);
instance.add("networking",interface_type);
JsonArray instances = new JsonArray();
instances.add(instance);
JsonObject launch_plan = new JsonObject();
launch_plan.add("instances", instances);
Please tell how does this code has to be changed in order to get the output asked above.
JsonObject launch_plan = new JsonObject();
launch_plan.add("instances", instances);
These two lines create the JSON object with curly braces. You don't need them, you can just remove them and use instances, which doesn't have curly braces as it's a json array and not a json object.
JsonObject ipnetwork = new JsonObject();
ipnetwork.addProperty("ipnetwork", ipNetworkName);
JsonObject interface_type = new JsonObject();
interface_type.add("eth0", ipnetwork);
JsonObject instance = new JsonObject();
instance.addProperty(imageListCmdText, "/oracle/public/oel6");
instance.addProperty("label","test_higgs");
instance.addProperty("shape","small");
instance.addProperty("name","/"+customerName);
instance.add("networking",interface_type);
JsonArray instances = new JsonArray();
instances.add(instance);
// not needed
//JsonObject launch_plan = new JsonObject();
//launch_plan.add("instances", instances);

Categories