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");
Related
I have a JSON object as shown bellow.I would like to delete the value of the JSON array in the JSON Object using java.I tried using javascript and did it but I am confused with Java.
{
"aaa":"0px",
"bbb":"sadsda",
"ccc":
{
"ddd":
{
"eee":"initial","dsa":"none","asd":"none","caption":"","type":"image","title":"test.txt","align":"center","resolution":null,"captionMargin":"0px auto","href":"ttt/bbb.zzz?cfr=148c273959c9&od=1572cfa","componentbottombordersize":"none","height":null,"border":"0","padding":1,"das":"","src":"ooo","alt":"test.txt","componentbgcolor":"transparent","yandex":null,"target":"_self","hhhh":"none","size":"F","google":"none","microsoft":"100%","name":""
},
"freshdesk":
{
"oooo"
}
},
"width":600,
"zarket":
{
"array":["value1","value2"]
},
"type":"mailchimp",
"height":251
}
I want to delete value1 of array.How Can I do it using java?
Include this in maven
https://mvnrepository.com/artifact/com.google.code.gson/gson
Try this
Gson gson = new GsonBuilder().create();
YourJsonObject yourObj = gson.fromJson(reader, YourJsonObject.class);
if(yourObj.getZarket()!=null && yourObj.getZarket().getArray()!=null){
yourObj.getZarket().getArray().remove("value1");
}
// Assuming you will create a class YourJsonObject with the above attributes of json and the array attribute will be a list. if its an array, remove by searching the value in an array using iterations
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
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/
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.
I am using Java to parse a JSON response from a server. My end goal is to have the data from results in an Array. Currently I am using this to try and get the results:
JSONArray jArray = myResponse.getJSONArray("results");
This code fails because it is looking for an array of objects, rather than an array of strings:
org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject
This is my server's JSON Response:
{
status: "OK",
results: [
"blah",
"bleh",
"blah"
]
}
Is there a simple way to get the "results" value into an array? Or should I just write my own parser.
Thanks
---------- UPDATE ----------
Looks like my problem was actually occuring somewhere else, and not where the JSON attribute "results" was being converted into a JSONArray.
Sorry and thanks for the answers, they helped me realize I was looking in the wrong spot.
This should be it. So you're probably trying to get JSONObject instead of String inside the results aarray.
JSONObject responseObject = new JSONObject(responseString);
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i=0; i<resultsArray.length(); i++)
String resultString = resultsArray.getString(i);
As you will probably have more properties, than only the String[] result, I recommend to define a DTO like this:
public class Dto {
//of course you should have private fields and public setters/getters, but this is only a sample
public String status;
public List<String> results;//this can be also an array
}
And then in your code:
ObjectMapper mapper = new ObjectMapper();
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need