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/
Related
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");
I need to parse json which I get from YQL but I am having trouble as I am not getting the results I need. I am using simple json (https://code.google.com/p/json-simple/wiki/DecodingExamples) and trying to follow the documentation. The problem is the example they show are very limited (I am very new to json). I want to extract everything in the array (Sy, Date, O, H, L, C, and V ). In the documentation they show how to extarct elements from an array if the json object is just as an array, but I have an array + some extra stuff on top:
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
This is the full json object, how would I extract just the array?
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
{"array":[{"Sy":"Y","Date":"2010-03-10","O":"16.51","H":"16.94","L":"16.51","C":"16.79","V":"33088600"},
{"Sy":"Y","Date":"2010-03-09","O":"16.41","H":"16.72","L":"16.40","C":"16.53","V":"20755200"},
{"Sy":"Y","Date":"2010-03-08","O":"16.32","H":"16.61","L":"16.30","C":"16.52","V":"30554000"}
]}}}
i use https://code.google.com/p/org-json-java/downloads/list
this is simple
try{
String json = "JSON source";
JSONObject j = new JSONObject(json);
JSONArray arr = j.getJSONObject("query").getJSONObject("results").getJSONArray("array");
for(int i=0; i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
String sy = obj.getString("Sy");
String date = obj.getString("Date");
String o = obj.getString("O");
String h = obj.getString("H");
String l = obj.getString("L");
String c = obj.getString("C");
String v = obj.getString("V");
}
}
catch(JSONException e){
}
You have to extract the array you need piece by piece.
JSONParser parser=new JSONParser();
String s="{YOUR_JSON_STRING}";
JSONArray array=parser.parse(s).get("query") //"query"
.get("result") // "query->result"
.get("array"); // THE array you need
Note that you might need to use try...catch... block to deal with exceptions.
Since you are using java, I highly recommend gson, which is written by google. It can convert json to object directly, which means you don't need to get the array deep inside the json step by step. https://code.google.com/p/google-gson/
Generally speaking, you can use gson to parse json piece by piece with jsonparser or, convert the whole json to a object with gson.
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
I want to know if it is possible to check if some key exists in some jsonArray using java. For example: lets say that I have this json string:
{'abc':'hello','xyz':[{'name':'Moses'}]}
let's assume that this array is stored in jsnArray from Type JSONArray.
I want to check if 'abc' key exists in the jsnArray, if it exists I should get true else I should get false (in the case of 'abc' I should get true).
Thnkas
What you posted is a JSONObject, inside which there is a JSONArray. The only array you have in this example is the array 'xyz', that contains only one element.
A JSONArray example is the following one:
{
'jArray':
[
{'hello':'world'},
{'name':'Moses'},
...
{'thisIs':'theLast'}
]
}
You can test if a JSONArray called jArray, included inside a given JSONObject (a situation similar to the example above) contains the key 'hello' with the following function:
boolean containsKey(JSONObject myJsonObject, String key) {
boolean containsHelloKey = false;
try {
JSONArray arr = myJsonObject.getJSONArray("jArray");
for(int i=0; i<arr.length(); ++i) {
if(arr.getJSONObject(i).get(key) != null) {
containsHelloKey = true;
break;
}
}
} catch (JSONException e) {}
return containsHelloKey;
}
And calling that in this way:
containsKey(myJsonObject, "hello");
Using regular expressions will not work because of the opening and closing brackets.
You could use a JSON library (like google-gson) to transform your JSON Array into a java array and then handle it.
JSON arrays don't have key value pairs, JSON objects do.
If you store it as a json object you can check the keys using this method:
http://www.json.org/javadoc/org/json/JSONObject.html#has(java.lang.String)
If you use JSON Smart Library in Java to parse JSon String -
You can parse JSon Array with following code snippet -
like -
JSONObject resultsJSONObject = (JSONObject) JSONValue.parse(<<Fetched JSon String>>);
JSONArray dataJSon = (JSONArray) resultsJSONObject.get("data");
JSONObject[] updates = dataJSon.toArray(new JSONObject[dataJSon.size()]);
for (JSONObject update : updates) {
String message_id = (String) update.get("message_id");
Integer author_id = (Integer) update.get("author_id");
Integer createdTime = (Integer) update.get("created_time");
//Do your own processing...
//Here you can check null value or not..
}
You can have more information in - https://code.google.com/p/json-smart/
Hope this help you...