extract from JSON - java

"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

Related

I want to extract the value from JSON by same id one id using java

So the json look like this
{
"cover":"AddressBook",
"Addresses":[
{
"id":"1",
"NickName":"Rahul",
"ContactName":"Dravid",
"Company":"Cricket",
"City":"Indore",
"Country":"India",
"Type":"Address"
},
{
"id":"2",
"NickName":"Sachin",
"ContactName":"Tendulkar",
"Company":"Cricket",
"City":"Mumbai",
"Country":"India",
"Type":"Address"
}
]
}
I want to extract the data from the id = 1 using the JSON array, but I am not sure how to use the syntax or some other way the code I have is this :
JSONParser jsonParser = new JSONParser();
FileReader reader = new FileReader("AddressBook.json");
Object obj = jsonParser.parse(reader);
address = (JSONArray)obj;
You have to loop through the "Addresses" array.
JSONObject addressBook = (JSONObject) jsonParser.parse(reader);
JSONArray addresses = (JSONArray) addressBook.get("Addresses");
JSONObject address = null;
for (Object find : addresses) {
if (((JSONObject) find).get("id").equals("1")) {
address = (JSONObject) find;
}
}
System.out.println(address.toJSONString());
Output
{"Company":"Cricket","Type":"Address","Country":"India","id":"1","City":"Indore","NickName":"Rahul","ContactName":"Dravid"}

reading data from nested JSON Object using java

i am struggling with reading some values from JSON object which i get it when i hit REST API..
MY GOAL: i need to iterate over each set of data inside data object array check the value of TRAN_ID and take action accordingly.
below is the format of data
{
"data": [
{
"CUST_ID": "CUST7",
"EXPRY_DATE": null,
"PARAMS": "[{TRAN_IND:savings},{TRAN_TYP:Debit},{country:US}]"
},
{
"CUST_ID": "CUST8",
"EXPRY_DATE": null,
"PARAMS": "[{TRAN_IND:current},{TRAN_TYP:Debit},{country:US}]"
}
]
}
it looks easy and i have tried multiple solutions out there on internet but i dont know it doesnt work for me and i get below error while reading "PARAMS" and converting it to JSONArray for further processing
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray
What i have tried:
private static void jsonParser(String jsonStr) throws ParseException {
JSONObject data= (JSONObject)JSONValue.parse(jsonStr );
JSONArray jsonObj = (JSONArray)data.get("data");
JSONObject JsonRow = (JSONObject)jsonObj.get(0);
JSONArray servParam= (JSONArray) JsonRow.get("PARAMS");
String tran_ind=(String) servParam.get(0);
System.out.println( tran_ind);
}
I'm guessing this is what you what?
try{
JSONObject obj = new JSONObject(sample);
JSONArray data = obj.getJSONArray("data");
for(int i=0; i<data.length(); i++){
JSONObject detail = data.getJSONObject(i);
detail.getString("CUST_ID"); //here is the customer id
detail.getString("EXPRY_DATE"); //here is the exp date
JSONArray params = detail.getJSONArray("PARAMS");
for(int j=0; j<params.length(); j++){
// {TRAN_IND:current},{TRAN_TYP:Debit},{country:US}
JSONObject res = params.getJSONObject(j);
String tran_ind = res.toString();
String tran_type = res.toString();
String country = res.toString();
out.println(tran_ind + " " +tran_type + " " + country);
}
}
}catch (JSONException ex){
ex.printStackTrace();
}
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray
=> Because you are trying to parse String value "[{TRAN_IND:savings},{TRAN_TYP:Debit},{country:US}]" into the JsonArray by code:
JSONArray servParam= (JSONArray) JsonRow.get("PARAMS");
Params seems to be a String, actually.
Don't write your own parser. If you only need to read that string in each element of the array, I would simply cast the whole JSON to a Map with Jackson:
HashMap<String,Object> parsed =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
and then iterate over the "data" element (which would be a list of maps).
List<Map> data = (List) parsed.get("data");
The real problem is that those are not nested JSON strings. That would be
"PARAMS": "[{\"TRAN_IND\":\"current\"},{\"TRAN_TYP\":\"Debit\"},{\"country\":\"US\"}]"
so "text" parts are surrounded by "-s inside (which have to be escaped as \"-s).
In that case you could write
String json=
"{\n"+
" \"data\": [\n"+
" {\n"+
" \"CUST_ID\": \"CUST7\",\n"+
" \"EXPRY_DATE\": null,\n"+
" \"PARAMS\": \"[{\\\"TRAN_IND\\\":\\\"savings\\\"},{\\\"TRAN_TYP\\\":\\\"Debit\\\"},{\\\"country\\\":\\\"US\\\"}]\"\n"+
" },\n"+
" {\n"+
" \"CUST_ID\": \"CUST8\",\n"+
" \"EXPRY_DATE\": null,\n"+
" \"PARAMS\": \"[{\\\"TRAN_IND\\\":\\\"current\\\"},{\\\"TRAN_TYP\\\":\\\"Debit\\\"},{\\\"country\\\":\\\"US\\\"}]\"\n"+
" }\n"+
" ]\n"+
"}";
// Print input for clarity:
System.out.println(json);
JSONObject data= (JSONObject)JSONValue.parse(json);
JSONArray jsonObj = (JSONArray)data.get("data");
JSONObject JsonRow = (JSONObject)jsonObj.get(0);
// parse nested JSON
JSONArray servParam= (JSONArray)JSONValue.parse((String)JsonRow.get("PARAMS"));
// array element is an object ({"TRAN_IND":"savings"}), so toString has to be used:
String tran_ind=servParam.get(0).toString();
System.out.println(tran_ind);
(The backslash-heaps are there because double-quotes had to be escaped in source code, and also the suggested escaped double quotes. So they would not appear in a JSON file. Try the code in action, it prints the JSON it works on)
So (JSONArray)JSONValue.parse((String)JsonRow.get("PARAMS")) would get and parse the nested JSON.
But now you either have to rework the code what generates your input, or parse the nested non-JSON manually.
You can use below code for parsing.
String servParam = (String) JsonRow.get("PARAMS");
String servParamSplitted[] = servParam.substring(1, servParam.length() - 1).split(",");
String traind_id[] = servParamSplitted[0].substring(1, servParamSplitted[0].length() - 1).split(":");
String train_id=traind_id[1];
I like to add that your JSON should be like below format.
{
"data": [
{
"CUST_ID": "CUST7",
"EXPRY_DATE": null,
"PARAMS": [{"TRAN_IND":"savings"},{"TRAN_TYP":"Debit"},{"country":"US"}]
},
{
"CUST_ID": "CUST8",
"EXPRY_DATE": null,
"PARAMS": [{"TRAN_IND":"current"},{"TRAN_TYP":"Debit"},{"country":"US"}]
}
]
}
So, we can parse it using below code.
JSONArray servParam = (JSONArray) JsonRow.get("PARAMS");
JSONObject jsonObjectTrainID = (JSONObject) servParam.get(0);
String TrainIDValue = (String) jsonObjectTrainID.get("TRAN_IND");

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());
}

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);

Extract json subset with few attributes from the main json

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.

Categories