JSON object retrieving sub values - java

Below is my json object.
{
"result":"ok",
"data":{
"buy":174.03,
"sell":160.64,
"timestamp":"2017-12-24T08:46:45.487+00:00"
}
}
I parse it using code and try outputting the value:
JSONObject json = new JSONObject(jsonValue);
System.out.println(json.getString("result"));
System.out.println(json.getJSONObject("data").getString("buy"));
I can print out the value of result.
But how do I print out the value of data. buy ?
I get error
org.json.JSONException: JSONObject["buy"] not a string.

buy is a double value, not a string. You will have to cast it into a string.
System.out.println(json.getJSONObject("data").getDouble("buy").toString());

buy is not a string because it is not quoted. Try getDouble("buy").

Related

Is toString() mandatory while accessing the individual element of a JSON object in Java

I am quite new to Java and trying to understand the effect of using toString() while accessing the individual string elements of JSON object in Java.
Below are the steps followed:
Parse the JSON data. Let's assume only string elements are there in parsed JSON data.
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(json_data);
{
"firstname" : "new",
"lastname" : "human",
"id" : "some_id"
}
Try to access the individual elements.
Access without toString():
Public static String firstname = jsonObj.get("firstname");
Access with toString():
Public static String firstname = jsonObj.get("firstname").toString();
I do not see a difference when I try to print the data.
However I would like to know the difference between the above 2 methods, and also will there be any issues if I use without toString() in this particular case.
Appreciate your help.
Thank you
When you have some Int or other type of data type variables in your model class and you want to parse it into a string so for that we use toString(), it will convert int or any other data variable into a string, in your case here you already have string so no need to change again and again and JSON uses string variables when it comes from backend so that the purpose.
toString() returns string representation of property/object on which this method is called.
Whenever we print an object reference, it invokes the toString() method internally as a result , it is not making difference.
Because you are using Json, there is no difference.
You can use the Option, you like more

how to remove the slashes from json key while converting object into string

I'm trying to convert JSON object into string by doing the below
JSONObject object = new JSONObject();
object.put("video", data);
array1.add( object.toString().replace("\\\\"," "));
Actual result
["{\"photos\":\"/contests/1/images/1.png\"}",
{\"photos\":\"/contests/1/images/2.png\"}"]
Expected result
["{"photos":"/contests/1/images/1.png\"}","
{"photos":"/contests/1/images/2.png\"}"]
not able to remove the slashes from key
Use replaceAll instead of replace
replaceAll("\\\\", "")
When you want to replace all the occurences with .replace, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.
Please use:
.replace("/\\/g","")
Alternatively, replaceAll can be used as #Code_Mono suggested
The Code_Mode mentioned is correct one.
Because String is immutable. Make sure that you put it right place.
You can refer code bellow for more detail:
public static void main(String[] args) {
String json = "[\"{\\\"photos\\\":\\\"/contests/1/images/1.png\\\"}\", {\\\"photos\\\":\\\"/contests/1/images/2.png\\\"}\"]";
json.replaceAll("\\\\","");
System.out.println(json);
String jsonReplace = json.replaceAll("\\\\","");
System.out.println(jsonReplace);
}
Output value:
["{\"photos\":\"/contests/1/images/1.png\"}", {\"photos\":\"/contests/1/images/2.png\"}"]
["{"photos":"/contests/1/images/1.png"}", {"photos":"/contests/1/images/2.png"}"]

how to correctly pick the json structure

Hi i have a php script that input user data into mysql and from mysql i get the results in an array and finally to json format by json_encode functino of PHP. The contents of the file are provided below.
[{"priority":"1","rule_body":"person(?x),pid(?y),haspid(?x,?y)","cons":"patient(?x)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"}]
However now i need to get the json read in the JAVA and for ease i copy and paste the contents of the json file to string. I am able to read the contents but the positions has changed to the following sequence
here is the output
LENGTH IS____7
{"priority":"1","boolean":"1","rule_body":"person(?x),pid(?y),haspid(?x,?y)","cons":"patient(?x)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
as you can see that the boolean has to be in the end but it pops up on the second number. i treid differenct codes from tutorials and did some my own as below but the result is same: help is needed in this matter.
jsonInput=[....as shown above the json contents....]
JSONArray ja = new JSONArray(jsonInput);
System.out.println("LENGTH IS____"+ja.length());
for(int x=0;x<ja.length();x++)
{
JSONObject jb = ja.getJSONObject(x);
System.out.println(jb);
}
System.out.println("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKK");
JSON doesn't specify an order for keys As Adrian Smith said :
JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.
You probably use org.json. You can use the getString("myKey") to access the value in your JSONObject without knowing his position.
An other solution is to create a class that represents your data:
public class myClass{
private int priority;
private String rule_body;
private String cons;
private String boolean; //STRING ! 1 is not a valid boolean value.
}
Then create an ArrayList of your class and deserialize your JSON in it with Gson.
Gson myGsonTool = new Gson();
ArrayList<myClass> myData = gson.fromJson(myJsonString, ArrayList<myClass>.class);
Then, you have a POJO with all your data. You can access easily to your data now:
//If i want the value of rule body:
myData.get(0).getRule_Body();
I do not know the purpose of your program, so this is maybe not the best solution.
Edit: Gson maintains the order of records.

How can I deserialize JSON to an object with a HashMap attribute?

Right now I am using Gson to deserialize JSON to Object.
The JSON looks like this:
[
{
"hash":"c8b2ce0aacede58da5d2b82225efb3b7",
"instanceid":"aa49882f-4534-4add-998c-09af078595d1",
"text":"{\"C_FirstName\":\"\",\"ContactID\":\"2776967\",\"C_LastName\":\"\"}",
"queueDate":"2016-06-28T01:03:36"
}
]
And my entity object looks like this:
public class AppCldFrmContact {
public String hash;
public String instanceid;
public HashMap<String,String> text;
public String queueDate;
}
If text was a String data type, everything would be fine. But then I wouldn't be able to access different fields as I want to.
Is there a way to convert given JSON to Object I want?
The error I am getting is: Expected BEGIN_OBJECT but was STRING at line 1 column 174, which is understandable if it cannot parse it.
The code doing the parsing:
Type listType = new TypeToken<List<AppCldFrmContact>>() {
}.getType();
List<AppCldFrmContact> contacts = gson.fromJson(response.body, listType);
For you expected result, JSON data should be like below format,
[
{
"hash":"c8b2ce0aacede58da5d2b82225efb3b7",
"instanceid":"aa49882f-4534-4add-998c-09af078595d1",
"text":{"C_FirstName":"","ContactID":"2776967","C_LastName":""},
"queueDate":"2016-06-28T01:03:36"
}
]
You are getting this error because text field is a JSON map serialized to the string. If it is an actual your data and not a just an example, you can annotate a field with #JsonDeserialize and write your own custom JsonDeserializer<HashMap<String,String>> which will make deserialization 2 times.

Setting a default value for empty json field

I have to parse a json whom a field can be empty:
{"fullField":"ok","canBeEmpty":""}
if I try to parse this string overall parsing fails with a "no value for canBeEmpty".
For each json item I execute:
json_data.getString("field"); //throws exception if empty
I'd like to still keep the parsing, setting the canBeEmpty value to a default string...is it possibile?
you can use JSONObject.JSONObject(String name) to check if any name is exist or not in json object as:
if(JSONObject.isNull("field")){
// do something here
}
else{
//do something here
}

Categories

Resources