I've got the following json code stored in a java String:
String str = {"posts":[{"key":"key1","value":"x"},{"key":"key2","value":"0"},{"key":"key3","value":"y"}]}
Is there a way to extract the values from the string using JSONObject or should I use the old school method:
String[] parts = str.split("\"");
In my case the values are stored in the array at the positions: parts[9], parts[17] and parts[25].
It works well so far, but I wonder if I could use JSONObject for that task?
Using JSONObject (from the org.json package, JSON-java), you can easily extract values.
final JSONObject jsonObject = new JSONObject(str);
final JSONArray posts = jsonObject.getJSONArray("posts");
final Collection<String> values = new ArrayList<>(posts.length());
for (int i = 0; i < posts.length(); i++) {
final JSONObject post = posts.getJSONObject(i);
values.add(post.getString("value"));
}
// values = [x, 0, y]
I'd absolutely avoid any kind of manual String manipulation.
Use Gson library provided by google if you are using Java
https://github.com/google/gson
Here you can convert your java to Json and Json back to java objects seamlessly.
Related
I have a java project in which I take a JSON and read its contents. I'm using org.json libraries and I would like to iterate through JSONObjects which are nested in a JSONArray, which is nested in a JSONObject. I keep getting this error though: JSONArray initial value should be a string or collection or array. I'm specifically getting the JSON from a web source, but here is an example of one: http://jsonblob.com/1062033947625799680
I'm particularly concerned about the fact that each player profile is unnamed, but there may be a simple fix for that.
I'd like to get access to each player profile and here is what I have that is causing an error:
import org.json.*;
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = new JSONArray(JSON.getJSONArray("data"));
for(int z = 1; i<data.length(); i++)
{
JSONObject ply = new JSONObject(data.getJSONObject(z));
System.out.println(ply.toString());
}
I have a feeling I just don't fully understand the terminology of JSON and/or the library that I'm using, but any help is appreciated.
Try this instead:
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = new JSONArray(JSON.getJSONArray("data"));
for(int i = 0; i<data.length(); i++) {
JSONObject ply = data.getJSONObject(i);
System.out.println(ply.toString());
}
It turns out I just have to access the particular element in one line:
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = JSON.getJSONArray("data");
for(int z = 0; z<data.length(); z++)
{
//JSONObject ply = new JSONObject(data.getJSONObject(z));
String name = data.getJSONObject(z).getString("skaterFullName");
System.out.println(name);
}
I have a java spring boot project that makes an REST API call and one element of the returned json is as follows:
"args": "[[\"element_1\"],[\"element_2\"],[\"{\\\"payload\\\":\\\"{\\\"Header\\\": \\\"Header_title\\\", \\\"Content\\\": \\\"Content of the payload\\\"}\\\"}\"]]"
My objective is to get the JsonObject "payload". I can get the string using
JsonObject argString = (JsonObject) jsonParser.parse(originalJsonObject.get("args").toString());
(using the package com.google.gson.JsonObject) but I can't get the two-dimensional array out of the string.
The part of data that you've included actually is a key args with a string value [[\"element_1\"],[\"element_2\"],[\"{\\\"payload\\\":\\\"{\\\"Header\\\": \\\"Header_title\\\", \\\"Content\\\": \\\"Content of the payload\\\"}\\\"}\"]]. So it is correct that you cannot get these contents decoded through a method on the existing Json, but you can take the string and parse it to a json array as follows:
JsonElement jsonElem = new JsonParser().parse(argString);
JsonArray jsonArray = jsonElem.getAsJsonArray();
for(int i = 0; i < jsonArray.size(); i++) {
System.out.println(jsonArray.get(i));
}
I want to get data from php file to Android using JSON. This is my code:
....
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
When I debug the program there is JSONException on this line:
JSONObject last = timeline.getJSONObject(0);
Data is {"a":1,"b":2,"c":3,"d":4,"e":5} and the Exception is:
org.json.JSONException: Value {"d":4,"e":5,"b":2,"c":3,"a":1} of type org.json.JSONObject cannot be converted to JSONArray
The exception message is quite explicit and a look at the JSON syntax diagrams should be illustrative. The JSON string that your code received is:
{"a":1,"b":2,"c":3,"d":4,"e":5}
This string represents an object, not an array. An example of an array would be this:
[1, 2, 3, 4, 5]
or even this:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Note that starting and closing brackets.
I think that you will find that the exception location is slightly misleading. I don't know if it is a result of some sort of lazy initialization or something else, but I believe that the cause is actually this line:
JSONArray timeline = new JSONArray(data);
Since the data string represents a JSON object and not an array, this operation is clearly impossible.
In Json arrays are described using [].
There you define an object with five attributes.
JSONArray timeline = new JSONArray(data);
// change JSONArray to JSONObject
JSONObject timeline = new JSONObject(data);// Like This
Your JSON data is not an array.
Your json response is in Object form, not in Array form.So you have to simply parse your json object. Suppose "data" is the JSONObject tag in response.
Following is the way of Parsing:
HttpEntity e = r.getEntity();
String result = EntityUtils.toString(e);
JSONObject response=new JSOBObject(result);
JSONOBject Data=response.getJSONObject("data");
int a=Data.getInt("a");
int b=Data.getInt("b");
int c=Data.getInt("c");
int d=Data.getInt("d");
int e=Data.getInt("e");
Thanks.
I'm trying to use the JSON library to consume twitter information from the get search feature. I'm getting the error:
A JSONArray text must start with '[' at 1 [character 2 line 1]
So it's basically in the wrong form. Some people are saying this needs to be an object but everytime I call the constructor it says that it can't take a String as input. How do I get this string into the form of a JSONArray so that I can access it's elements.
Here is my code:
URL twitterSource = new URL("http://search.twitter.com/search.json?q=google");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse JSON
System.out.println(urlContents);
JSONArray jsonArray = new JSONArray(urlContents);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
my print statement shows the string contains:
{"completed_in":0.318,"max_id":144850937012428800,"max_id_str":"144850937012428800","next_page":"?page=2.....................
This is a string in the form of a JSON object but it is not actually an object. It's still a string. I'm printing a String. HOw can I get this into an Object or better yet a JSONArray so that I can actually access its elements.
That's a JSON object, not an array.
In the client side, I have constructed a JSOnARRAY like this:
{"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
On the server side (java), I can retireve the values using :
jfilter = JSONValue.parse(jsonFilterStr); //jsonFilterStr={"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
JSONArray jFilterEntries = (JSONArray) jfilter.get("filterEntries");
for (int i=0;i<jFilterEntries.size();i++){
JSONObject jFilterEntry = (JSONObject) jFilterEntries.get(i);
String dataName = (String) jFilterEntry.get("dataName");
String filterValue = (String) jFilterEntry.get("filterValue");
}
But the existing app is using flex.json.deserializer and I am unable to achieve the same using flex.json.deserializer. How should I proceed?
I wish to do something like this:
JSONDeserializer jsonDeserializer = new JSONDeserializer();
jsonDeserializer.use(null, List.class);
List<Map<String,String>> lMap= (List<Map<String,String>>)jsonDeserializer.deserialize(params);
Remember the top object that wraps the array. You have to handle that as well. You have to tell it to expect a Map inside the List. To do that you have to specify the type contained in the list by using the path expression "values".
Map<String,List<Map<String,String>>> result = new JSONDeserializer<Map<String,List<Map<String,String>>>>()
.use("values",List.class)
.use("values.values", Map.class)
.deserialize( json);
List<Map<String,String>> filterEntries = result.get("filterEntries");
Updated: Add the new keyword, and made the generic types on the right match the left.