i get a json object via an api:
Gson gson = new Gson();
JsonObject users = gson.fromJson(reader, JsonObject.class)
this is my json object:
{"users":"[{\"user_id\": \"100011\", \"name\": \"Tim Clark\"}, {\"user_id\": \"100083\", \"name\": \"Timmy Kent\"}]"}
and i try to loop through all users
JsonArray usersArray = users.getAsJsonArray();
for (JsonElement ua : usersArray) {
JsonObject ua = ua.getAsJsonObject();
String name = ua.get("name").getAsString();
System.out.println(name);
}
also tried this
JsonArray usersArray = users.get("users").getAsJsonArray();
for (JsonElement ua : usersArray) {
JsonObject ua = ua.getAsJsonObject();
String name = ua.get("name").getAsString();
System.out.println(name);
}
But I get always exceptions like this
java.lang.IllegalStateException: Not a JSON Array: "[{\"user_id\": \"100011\", \" ....
In my opinion it is a valid json array, what to I miss?
Your JsonArray is between quotes: it's evaluated as a String
{"users":[{\"user_id\": \"100011\", \"name\": \"Tim Clark\"}, {\"user_id\":
\"100083\", \"name\": \"Timmy Kent\"}]}
should work (quotes inside the array don't need to be escapted as well, like "users")
Related
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");
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());
}
"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
I have json string data like:
{"contactlist":["{"id":"1","mobile":"186010855","name":"Intex"}","{"id":"212","mobile":"980067","name":"pari"}"]}
I want to fetch all data means id,mobile and name for all..
So, I have Contact Class :
public class Contact {
private String id;
private String name;
private String mobile;
//getters and settrs & constructors
}
and for fetching I have tried:
String stringdata=
"{"contactlist":["{"id":"1","mobile":"186010855","name":"Intex"}","
{"id":"212","mobile":"980067","name":"pari"}"]}";
try{
Contact contact1 = new Contact();
contact1 = new Gson().fromJson(contactreceive, Contact.class);
Contact contact = new Contact(contact1.getId(),contact1.getName(),
contact1.getMobile());
System.out.println (contact);
}catch(Exception e){
}
But I can not fetch data like this..how can I fetch this json data?
Your JSON is invalid, as per #ShubhamChaurasia 's comment. The following JSON validates:
{
"contactlist": [{
"id": "1",
"mobile": "186010855",
"name": "Intex"
},
{
"id": "212",
"mobile": "980067",
"name": "pari"
}]
}
Escape this in Java as you have already been shown (with \") and this will stop your JSON validation errors. I recommend combining this with #Joopkins ' or #JanTheGun 's answer.
A good site I use for JSON validation is http://jsonlint.com/.
You need to escape the double quotes to get a valid json string. Then you can read the json array like this:
String stringdata = "{\"contactlist\":[{\"id\":\"1\",\"mobile\":\"186010855\",\"name\":\"Intex\"},{\"id\":\"212\",\"mobile\":\"980067\",\"name\":\"pari\"}]}";
JsonElement jsonElement = new JsonParser().parse(stringdata);
JsonObject jsonOject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonOject.getAsJsonArray("contactlist");
for (JsonElement element : jsonArray) {
JsonObject obj = element.getAsJsonObject();
String id = obj.get("id").toString();
String name = obj.get("name").toString();
String mobile = obj.get("mobile").toString();
Contact contact = new Contact(id, name, mobile);
System.out.println("id: " + contact.getId());
System.out.println("name: " + contact.getName());
System.out.println("mobile: " + contact.getMobile());
System.out.println("");
}
You can convert the stringdata into a JSONArray containing a JSONObject for each contact.
JSONObject contactData = new JSONObject(stringdata);
JSONArray contactArray = contactData.getJSONArray("contactlist");
//Create an array of contacts to store the data
Contact[] contacts = new Contact[contactArray.length()];
//Step through the array of JSONObjects and convert them to your Java class
Gson gson = new Gson();
for(int i = 0; i < contactArray.length(); i++){
contacts[i] = gson.fromJson(
contactArray.getJSONObject(i).toString(), Contact.class);
}
Now you have an array of Contacts from your raw JSON data.
JSONObject contactData = new JSONObject(stringdata);
JSONArray contactArray = contactData.getJSONArray("contactlist");
for(int i=0;i<contactArray .length;i++){
JSONObject jsonObject=contactArray.getJSONObject(i));
String id=jsonObject.getString("id")
String key=jsonObject.getString("key")
}
I am using the following library to parse an object:
{"name": "web", "services": []}
And the following code
import com.json.parsers.JSONParser;
JSONParser parser = new JSONParser();
Object obj = parser.parseJson(stringJson);
when the array services is empty, it displays the following error
#Key-Heirarchy::root/services[0]/ #Key:: Value is expected but found empty...#Position::29
if the array services has an element everything works fine
{"name": "web", "services": ["one"]}
How can I fix this?
Thanks
Try using org.json.simple.parser.JSONParser
Something like this:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(stringJson);
Now to access the fields, you can do this:
JSONObject name = jsonObject.get("name"); //gives you 'web'
And services is a JSONArray, so fetch it in JSONArray. Like this:
JSONArray services = jsonObject.get("services");
Now, you can iterate through this services JSONArray as well.
Iterator<JSONObject> iterator = services.iterator();
// iterate through json array
while (iterator.hasNext()) {
// do something. Fetch fields in services array.
}
Hope this would solve your problem.
Why do you need parser?
try this:-
String stringJson = "{\"name\": \"web\", \"services\": []}";
JSONObject obj = JSONObject.fromObject(stringJson);
System.out.println(obj);
System.out.println(obj.get("name"));
System.out.println(obj.get("services"));
JSONArray arr = obj.getJSONArray("services");
System.out.println(arr.size());
I solve the problen with https://github.com/ralfstx/minimal-json
Reading JSON
Read a JSON object or array from a Reader or a String:
JsonObject jsonObject = JsonObject.readFrom( jsonString );
JsonArray jsonArray = JsonArray.readFrom( jsonReader );
Access the contents of a JSON object:
String name = jsonObject.get( "name" ).asString();
int age = jsonObject.get( "age" ).asInt(); // asLong(), asFloat(), asDouble(), ...
Access the contents of a JSON array:
String name = jsonArray.get( 0 ).asString();
int age = jsonArray.get( 1 ).asInt(); // asLong(), asFloat(), asDouble(), ...