Java JSON printing [duplicate] - java

This question already has answers here:
Printing JSON values
(3 answers)
Closed 9 years ago.
JSON code (test2) for reference
{
"forecast": {
"txt_forecast": {
"date": "8: 00AMMST",
"forecastday": [
{
"period": 0,
"icon": "partlycloudy",
"icon_url": "http: //icons-ak.wxug.com/i/c/k/partlycloudy.gif",
"title": "Thursday",
"fcttext": "Partlycloudy.Highof63F.Windslessthan5mph.",
"fcttext_metric": "Partlycloudy.Highof17C.Windslessthan5km/h.",
"pop": "0"
}
]
}
}
}
Java code for reference
Object obj = parser.parse(new FileReader("C:\\Users\\User\\Desktop\\test2.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("forecast").toString();
System.out.println(name);
When I use this java code It prints out the entirety of "forecast" (IE, it prints out the date, period, icon, title, ect...). My question is, how do I print out specific parts of the JSON code without printing out ALL of the code. I'm using JSON-SIMPLE, thanks.

Object obj = parser.parse(new FileReader("C:\\Users\\User\\Desktop\\test2.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject forecast = jsonObject.get("forecast");
JSONObject txt__forecast = jsonObject.get("txt_forecast");
JSONArray forecastday = jsonObject.getJSONArray("forecastday");
JSONObject forecastIdx0 = forecastday.get(0);
int period = forecastIdx0.getInt("period");
Stting title = forecastIdx0.getString("title");
Normally you would not store them on every call. I just did this to show what each of the get calls return. As you can tell this is pretty verbose. If you are working with JSON in more than a simple way you benefit greatly in using an object deserialization library such as GSON that allows you to straight deserialize into a pre defined object.
For reference refer to http://www.json.org/javadoc/org/json/JSONObject.html it is the official Json library that is used for low level manipulation and traversal of json. Its used everywhere and by every thing that interacts with json.

Related

Null pointer observed while trying to fetch the object value from JSON array

I'm trying to loop the calls: JSON array and trying to fetch the machine details JSON object which is present under calls JSON array list as like below:
{
"<dynamicValue>":{
"type":"CORR-ID",
"tags":[
{
"name":"9VB6454145983212H",
"flags":[
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary":[
{
"colo":"lvs",
"pool":"amazon_paymentsplatformserv",
"machine":"stage2utb29958"
},
{
"colo":"lvs",
"pool":"amazon_elmoserv",
"machine":"msmamoserv_0"
},
{
"colo":"lvs",
"pool":"amazon_xopaymentgatewayserv",
"machine":"msmastmentgatewayserv_1"
},
{
"colo":"lvs",
"pool":"amazon_paymentapiplatserv",
"machine":"msmaentapiplatserv_2"
},
{
"colo":"lvs",
"pool":"amazon_userlifecycleserv_ca",
"machine":"stage2utb91581"
},
{
"colo":"lvs",
"pool":"amazon_dafproxyserv",
"machine":"msmasfproxyserv_1"
},
{
"colo":"lvs",
"pool":"paymentserv",
"machine":"te-alm-15757_paymentexecutionserv_0",
"calls":[
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmgementserv_ca_20"
},
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmasgementserv_ca_4"
}
]
}
]
}
}
The above JSON file which I stored in String variable and trying to fetch the machine details which is under calls: JSON ARRAY by using below code.
Code:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONObject getCalSummary = (JSONObject) object.get("callSummary");
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
System.out.println(arrays.size()); // return null pointer
}
Error:
java.lang.NullPointerException: null
at com.online.amazon.hadoop.cal.swagger.utils.Utils.getHttpUrlformachineList(Utils.java:112) ~[classes/:na]
If you notice that calls Array List will not be available in all the callSummary JSON Array, and It will be dynamic and can be available under any component that listed above.
So I just want to dynamically get the calls: JSON array and iterate and fetch machine details.
Can someone help me to achieve this?
Note: I'm using JSON-Simple library to parse and iterate the JSON. It would be great if I get solution on the same.
Updated:
I also tried to create callSummary as JSON array and loop that array to get each JSON object and tried to find the calls but this is also leads to Null pointer.
Also the calls json array is not index specific. It can be anywhere in the payload. It may or may not be there in the payload. I just need to handle if it's exist in any of the component then I need to fetch that machine details
change
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
to
JSONArray arrays= getCalSummary.getJSONArray("calls")
and all other functions where you get objects instead of "get" you should use "getJSONObject", "getString" etc.. then you dont have to cast,
also im pretty sure its not arrays.size() its arrays.length() if you are using package org.json.JSONArray but since key "calls" doesnt exist in every "callSummary" you should check if its null or not before.
You should match the types as specified in your JSON string:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONArray getCalSummary = (JSONArray) object.get("callSummary"); // callSummary is a JSONArray, not JSONObject
for (int i = 0; i < getCalSummary.length(); i++) {
JSONObject obj = getCalSummary.getJSONObject(i);
if (obj.has("calls")) {
// grab calls array:
JSONArray callsArray = obj.getJSONArray("calls");
}
}
}
Here, you should also check your JSON values with .has(...) method to avoid getting JSONException if a field doesn't exists in your JSONObject.

Android - JSON no value for artists (echonest api) [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
Using a GET request to get an artist (search) from the echonest API I get the following JSON back:
{
"response": {
"status": {
"version": "4.2",
"code": 0,
"message": "Success"
},
"artists": [
{
"id": "ARR3ONV1187B9A2F49",
"name": "Muse"
}
]
}
}
I want to convert the above JSON string to a JSON object like this:
jso = new JSONObject(JSONstring);
Then I want to save both the id and name into strings, first I want to save the array of artists in a JSON array like this:
jsa = jso.getJSONArray("artists");
This is the moment where I get the JSON error no value for artists.
I can't figure out what is going wrong here, can anyone help me in the right direction? Thanks.
The json array artists is inside the json object response
So you have to get the Json object with key response first, then get
json array artists from it
jsa = jso.getJSONObject("response");
jsa.getJSONArray("artists");
Artists array is response JSON object so first you to get response data and then after you get artists JSON array like below
JSONObject response = jso.getJSONObject("response");
jsa = response.getJSONArray("artists");
Hope it will help you !!
The reason you are not getting value is because you are not following nesting.
You have to receive object like its nested. First you have to goto MainObject and then data is stored in "response" object. After that you can receive array from "response" object.
You must follow nesting of JSON like it designed.
Try Doing it this way..
JSONObject mainObj = new JSONObject(JSONstring);
// Try to get Response Object from main JSON object then try to get array from it.
JSONObject responseObj = mainObj.getJSONObject("response");
// getting array from response object.
JSONArray artistArr = responseObj.getJSONArray("artists");
Or you can do it in one line..
JSONArray artistArr = mainObj.getJSONObject("response").getJSONArray("artists");
You have it nested within the response object so you are currently trying to access "artists" like it is the 'parent' object but this is in fact a child of the "response" object. You will need to first retrieve the json object to "response" and then get the json array "artists".
"artists" array is inside the "response" object, you can get the "artists" array using following code:
jsonArray = jso.getJSONObject("response").getJSONArray("artists");

Parse JSON using JSON Object

MY JSON response body from a service as follows
{
"Employee": {
"Name": "Demo",
"applied": true
}
}
I want to parse using JSON Object in Java.
i did like this
JSONObject obj = new JSONObject(String.valueOf(responseBody));
//responbosy is a JSONObject type
obj.getString("Employee[0].name");
Please suggest how to do that
Employee is not an array, only JSONObject
So you have do something like that:
obj.getJSONObject("Employee").getString("Name");
I Think you want to have the name, yes?
Anyway, you can access it by using:
JSONObject obj = new JSONObject(String.valueOf(responseBody));
JSONObject employee = new JSONObject(obj.getJSONObject("Employee"));
employee.getString("Name");
employee.getBoolean("applied");
Reason for this is:
Everything between
{}
is an JSONObject. Everything between
[]
means it's an JSONArray.
In your String
{
"Employee": {
"Name": "Demo",
"applied": true
}
}
You've an JSONObject because of starting with {}. Within this JSONObject you have an Propertie called "Employee" which has another JSONObject nested.
Be Carefull: applied is from type boolean, since it's true/false without "". If there's a number you should get it using getInteger(). if it's a boolean you can get it using getBoolean() and elsehow you should get it using getString().
you can see all available Datatypes at http://en.wikipedia.org/wiki/JSON

How to store JSON response in an array list? [duplicate]

This question already has answers here:
Converting JSONarray to ArrayList
(23 answers)
Closed 8 years ago.
I want to store a JSON response in array list so that it will be easy to fetch data and assign it to other variables.
This is my JSON response:
{
"statusCode":"1001",
"message":"Success",
"response":{
"holidays":[
{
"holidayId":78,
"year":2015,
"date":"2015-01-01",
"day":"Thrusday",
"occasion":"New Year Day",
},
{
"holidayId":79,
"year":2015,
"date":"2015-01-15",
"day":"Thrusday",
"occasion":"Pongal/Sankranthi",
},
{
"holidayId":80,
"year":2015,
"date":"2015-01-26",
"day":"Monday",
"occasion":"Republic Day",
}
],
"year":0
}
}
This is the way I am fetching data from the response:
JSONObject jobj = new JSONObject(result);
String statusCode = jobj.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
System.out.println("SUCCESS!");
String response = jobj.getString("response");
JSONObject obj = new JSONObject(response);
String holidays = obj.getString("holidays");
ArrayList<HolidayResponse> holidayResponse = holidays; //This stmt. shows me error
}
How do I solve this issue? Please help me.
that is because of a JSON parse exception:
the holidays is a JSON array.Hence the correct way would be:
JSONObject obj = new JSONObject(response);
JSONArray holidays = obj.getJSONArray("holidays");
look here to convert that to array list.
Instead of all this hassle,you could use Gson or Jackson

What Format is this List in? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 8 years ago.
I'm receiving data in the format:
"result": {"FirstData": {"One": 1, "Two": 2,...
First of all, what is this called usually in Java (2D array)?
Secondly, how do I loop over this to extract the strings?
I understand that if I only had "FirstData" in my array I can do:
public void onSuccess( String[] result)
{
for( String Name : result ) {
System.out.println(Name);
}
Going through the same logic for 2D arrays, it doesn't seem to print things out:
public void onSuccess( JSONObject result)
{ //Parse here
}
EDIT:
Yes it's JSON and it looks like the code has gson (google JSON) installed
EDIT 2:
ABOVE CODE NOW CORRECTED
JSON. Use a JSON parser to read the data. One popular parser for Java : google-gson
It looks kind of like JSON. JSON-strings is built like this:
Key: Values
However, Values can be new "key:values" so you can have:
"Key": ["InnerKey1":"Value1","Innerkey2","Value2"], "Key2": ["InnerKey1":"Value1","Innerkey2","Value2"] etc.
For you source:
JSONObject myJSONObject = new JSONObject("Your resultstring goes here");
JSONObject resultObject = myJSONObject.getJSONObject("result");
JSONObject FirstDataObject = resultObject.getJSONObject("FirstData"); //Object with JSONObjects "One","Two" etc
//Since the part " {"One": 1, "Two": 2,..." in your string isn't an JSONArray you cannot do the following but if it were like this "["One": 1, "Two": 2,..." your could do this:
JSONArray FirstDataArray = resultObject.getJSONObject("FirstData"); //Array with JSONObjects "One","Two" etc
JSONArray arr = resultObject.getJSONArray("FirstData");
for (int i = 0; i < arr.length(); i++)
{
String number = arr.getJSONObject(i).getString(0);
......
}
You can try using Google Gson, https://code.google.com/p/google-gson/. It can take JSON strings and convert them to Java objects.
Use a JSON parser for Java and you can probably convert it into objects. You can find a variety of Java-based JSON parsers on http://www.json.org/
This string is in the JSON format and hence it is recommended to use a JSON parser.
Read about JSON format in http://www.json.org/.
This link provides explains about JSON in java http://www.json.org/java/

Categories

Resources