Parsing JSON server response into JSON Array - java

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

Related

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

JSON Exception String cannot be converted to JSON Object

I am trying to parse json and running into a small problem.
my json string looks like this:
String json =
[
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}",
"{caption=adsf, url=/storage/emulated/0/DCIM/Camera/20140330_103412.jpg}"
]
and my code so far looks like this:
try {
JSONArray jsonObj = new JSONArray(json);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String img = c.getString("url");
String cap = c.getString("caption");
But its throwing an exception type java.lang.String cannot be converted to JSONObject
What am I doing wrong?
EDIT
If its helpful to anyone, I ended up using GSON to get my json in the correct expected format like this:
Gson gson = new Gson();
String json = gson.toJson(mylist);
Your JSON array contains elements like
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}"
which is a String not a JSON object. You can't therefore try to retrieve it as a JSONObject.
Seems like you're getting JSON that isn't in the format you expected. Even if you got rid of the "" around it, it still wouldn't be valid JSON, so I don't understand its purpose enough to help you.

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/

nameValuePair key added in new JSONObject

When I am building a json object from string it is appended with a root key "nameValuePairs".
String curStr = "{\"e\": \"{}\", \"f\": \"{}\", \"g\": \"{}\"}";
JSONObject oldObj = new JSONObject(curStr);
results to
{"nameValuePairs":{"b":"{}","c":"{}","a":"{}"}}
Why?
Any way to prevent that?
Btw, I am using the string json to represent the actual json which I will use later.
First of all your json is syntactically correct but I guess you wished to represent objects as values, in your case the curly brackets are evaluated as simple strings:
String curStr = "{\"e\": \"{}\", \"f\": \"{}\", \"g\": \"{}\"}";
JSONObject oldObj = new JSONObject(curStr);
using a json like this instead will produce values as objects:
String curStr = "{\"e\": {}, \"f\": {}, \"g\": {}}";
JSONObject oldObj = new JSONObject(curStr);
Anyway, I've tried to create that JSONObject and then print a toString of it, and it will simply print the json, without any accessory name.
As you find out in the comment the problem was given by Gson, that will evaluate the JSONObject as a map. I've tried a little example and I've got "map" as field. Probably I've tried a different version of Gson.
Gson gson = new Gson();
String jsonStr = gson.toJson(oldObj);
result: {"map":{"f":"{}","g":"{}","e":"{}"}}
If you want to create a custom object and deserialize a json with Gson create a class with those properties and use the fromJson(String json, Class clazz) method
public class Test {
private String e;
private String f;
private String g;
}
and
Gson gson = new Gson();
Test myTestObj = gson.fromJson(curStr, Test.class);
Hope this will help you. :)
You can try jsonStringer instead.
Something like below code:
JSONStringer jObject = new JSONStringer()
.object()
.key("UserName").value(userNameValue)
.key("Name").value(nameValue)
.key("EmailId").value(emailIdValue)
.key("CountryId").value(contryIdValue)
.key("CountryName").value("") // It should be blank As Spanish Name is not set if User have App in Spanish
.key("State").value(stateValue)
.key("City").value(cityValue)
.key("ImageByteArray").value(imageBytes)
.endObject();
UPDATE
I have just use your code in my App and check it.
Its showing me the result as we have formed.
Result i am getting is:
{
"f": "{}",
"g": "{}",
"e": "{}"
}
Please check your packages you are importing.
For your reference i am importing below class to represent json object.
import org.json.JSONException;
import org.json.JSONObject;
Just import above class and see the result.
Let me know if you still have any query.

Categories

Resources