im struggling with json again :(
Here is the original response:
{"xml-fragment":{"workItem":{"#id":"251","#version":"74"},"presentation":{"#formIdenitifier":"1.0.0.201310151421/openspaceGWTPull_DefaultChannel/.default/Npda/NpdaProcess/UserReconcile/UserReconcile.gwt.json","#type":"GWT_FORM","#version":"1.0.0.201310151421","#activityName":"UserReconcile"},"workTypeDetail":{"#typePiled":"false","#pilingLimit":"0","#uid":"WT__RIoPEDWTEeOr4-yR8gXd7g","#version":"1.0.0.201310151421"},"payloadModel":{"serializedPayload":"{items:[{\"$param\":\"BankReconInput\",\"mode\":\"IN\",\"$value\":[{\"bankAccountTx_pk\":\"55213\",\"amount\":\"10099\",\"reference\":\"ImAmReference\",\"date\":\"2013-10-15\",\"reconType\":\"?\",\"amxcaseref\":\"pvm:0a12iq\",\"$type\":\"coza.npda.bom.BankTransaction\"}]}]}","#payloadMode":"JSON"}}}
i want to for example get value of amount from the serializedPayload. The problem is that it is not a json object. If i try:
obj = new JSONObject(jsonResp).getJSONObject("xml-fragment").getJSONObject("payloadModel");
this returns to me serializedPayload as a string and #payloadMode as a string.
i tried:
obj = new JSONObject(jsonResp).getJSONObject("xml-fragment").getJSONObject("payloadModel").getJSONObject("serializedPayload");
its confirms that serializedPayload is not a json object.
I looked at this example: http://developer.android.com/reference/org/json/JSONTokener.html
But its data is not as complex as mine and i am struggling to find java examples of how to do this.
Please can anyone help.
You don't need an example, you need to look at the JSON and think for a second.
serializedPayload is not a JSON object to begin with, it's really a string that has another piece of json encoded inside, sort of like the russian nesting dolls (frankly, it's an abomination).
You need to take the string, and then parse it again, using another JSONObject, sort of:
String payload = data..getJSONObject("xml-fragment").getJSONObject("payloadModel").getString("serializedPayload");
JSONObject theRealData = new JSONObject(payload);
Related
I'm using this code in Java:
JSONObject jsonObject = new JSONObject(response.body().string());
and it will lead to null when I put strings like
[{...},{...}, ..., {...}]
where {...} is a valid JsonObject.
What should I do? I guess json must begin with { and end with } always. That's because it's null. What should I do? Is there a way to make JSON library deal with this automatically? I can't control the place from where I receive this string of 'json array'.
Because the string you've given isn't an object, but an array.
You'll have to read it like that (using Java EE's JSON libraries):
JsonArray array = jsonReader.readArray();
Is there a way in Java/J2ME to convert a string, such as:
{name:"MyNode", width:200, height:100}
to an internal Object representation of the same, in one line of code?
Because the current method is too tedious:
Object n = create("new");
setString(p, "name", "MyNode");
setInteger(p, "width", 200);
setInteger(p, "height", 100);
Maybe a JSON library?
I used a few of them and my favorite is,
http://code.google.com/p/json-simple/
The library is very small so it's perfect for J2ME.
You can parse JSON into Java object in one line like this,
JSONObject json = (JSONObject)new JSONParser().parse("{\"name\":\"MyNode\", \"width\":200, \"height\":100}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("width"));
The simplest option is Jackson:
MyObject ob = new ObjectMapper().readValue(jsonString, MyObject.class);
There are other similarly simple to use libraries (Gson was already mentioned); but some choices are more laborious, like original org.json library, which requires you to create intermediate "JSONObject" even if you have no need for those.
GSON is a good option to convert java object to json object and vise versa.
It is a tool provided by google.
for converting json to java object use: fromJson(jsonObject,javaclassname.class)
for converting java object to json object use: toJson(javaObject)
and rest will be done automatically
For more information and for download
You can do this easily with Google GSON.
Let's say you have a class called User with the fields user, width, and height and you want to convert the following json string to the User object.
{"name":"MyNode", "width":200, "height":100}
You can easily do so, without having to cast (keeping nimcap's comment in mind ;) ), with the following code:
Gson gson = new Gson();
final User user = gson.fromJson(jsonString, User.class);
Where jsonString is the above JSON String.
For more information, please look into https://code.google.com/p/google-gson/
You have many JSON parsers for Java:
JSONObject.java
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONArray.java
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONStringer.java
A JSONStringer is a tool for rapidly producing JSON text.
JSONWriter.java
A JSONWriter is a tool for rapidly writing JSON text to streams.
JSONTokener.java
A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and JSONArray constructors to parse JSON source strings.
JSONException.java
A JSONException is thrown when a syntax or procedural error is detected.
JSONString.java
The JSONString is an interface that allows classes to implement their JSON serialization.
JSON official site is where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-lib which is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.
If you click the html links there you can find anything you want.
In short:
to create a json object and a json array, the code is:
JSONObject obj = new JSONObject();
obj.put("variable1", o1);
obj.put("variable2", o2);
JSONArray array = new JSONArray();
array.put(obj);
o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.
The reverse process is fairly simple, I mean converting a string to json object/array.
String myString;
JSONObject obj = new JSONObject(myString);
JSONArray array = new JSONArray(myString);
In order to be correctly parsed you just have to know if you are parsing an array or an object.
Use google GSON library for this
public static <T> T getObject(final String jsonString, final Class<T> objectClass) {
Gson gson = new Gson();
return gson.fromJson(jsonString, objectClass);
}
http://iandjava.blogspot.in/2014/01/java-object-to-json-and-json-to-java.html
Like many stated already, A pretty simple way to do this using JSON.simple as below
import org.json.JSONObject;
String someJsonString = "{name:"MyNode", width:200, height:100}";
JSONObject jsonObj = new JSONObject(someJsonString);
And then use jsonObj to deal with JSON Object. e.g jsonObj.get("name");
As per the below link, JSON.simple is showing constant efficiency for both small and large JSON files
http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
JSON IO is by far the easiest way to convert a JSON string or JSON input stream to a Java Object
String to Java Object
Object obj = JsonReader.jsonToJava("[\"Hello, World\"]");
https://code.google.com/p/json-io/
This is an old question and json-simple (https://code.google.com/p/json-simple/) could be a good solution at that time, but please consider that project seems not to be active for a while !
I suggest the Gson which is now hosted at: https://github.com/google/gson
If performance is your issue you can have a look at some benchmarks http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/ which compare.
Apart from www.json.org you can also implement your own parser using javacc and matching your personnal grammar/schema.
See this note on my blog : http://plindenbaum.blogspot.com/2008/07/parsing-json-with-javacc-my-notebook.html
I've written a library that uses json.org to parse JSON, but it will actually create a proxy of an interface for you. The code/JAR is on code.google.com.
http://fixjures.googlecode.com/
I don't know if it works on J2ME. Since it uses Java Reflection to create proxies, I'm thinking it won't work. Also, it's currently got a hard dependency on Google Collections which I want to remove and it's probably too heavyweight for your needs, but it allows you to interact with your JSON data in the way you're looking for:
interface Foo {
String getName();
int getWidth();
int getHeight();
}
Foo myFoo = Fixjure.of(Foo.class).from(JSONSource.newJsonString("{ name : \"foo name\" }")).create();
String name = myFoo.getName(); // name now .equals("foo name");
Just make a Json object in java with the following Json String.In your case
{name:"MyNode", width:200, height:100}
if the above is your Json string , just create a Json Object with it.
JsonString ="{name:"MyNode", width:200, height:100}";
JSONObject yourJsonObject = new JSONObject(JsonString);
System.out.println("name=" + yourJsonObject.getString("name"));
System.out.println("width=" + yourJsonObject.getString("width"));
Jackson for big files, GSON for small files, and JSON.simple for handling both.
I've a method that returns a 2d-array in java : public Object[][] getArray1() {}
I used println() to print it's content and i see that its well created.
On Javascript i assign this array to a var:
var content ="#{BDEStats.getArray1()}";
But i dont seem able to acess it's data. it always returns java.Lang.object; #... How can i do to display the content this array holds?
I've tried to cycle the array but i dont know how to refer to the objects it is holding. if i use content[1] to returns a char in that índex..! Kinda lost here
I think you may convert the array to JSON format before assigning it to javascript.
You can use some JSON framework to do this convert like:
JSON-lib
Jackson
Here a tiny Jackson demo:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
...
public static void main(String[] args) throws JsonProcessingException {
String[][] data = new String[1][2];
data[0][0] = "abc";
data[0][1] = "def";
System.out.println(new ObjectMapper().writeValueAsString(data));
}
This is the normal array String representation in Java, consisting in:
A number of [ based on the dimension
Either a letter for the primitive type (i.e. I for int), or L[fully qualified class name] for Objects
#
The array's hash code
For one-dimensional arrays, use java.util.Arrays.toString(myArray).
For multi-dimensional arrays, use java.util.Arrays.deepToString(myArray).
Edit (adding previous comment to answer)
You probably want to investigate JSON.parse to parse your Java array from JavaScript.
To turn a Java array into a string representation in a syntax which can be interpreted by a JavaScript engine, you need to turn it into the JavaScript Object Notation, or JSON for short.
There are many libraries available for Java to do this. Software recommendations are off-topic on Stackoverflow, but this article which compares 5 different libraries helped me to pick one for my project.
On the JavaScript side, you just have to use var content = JSON.parse(stringFromJava).
Or when you generate the JS code procedurally on the Java side, you can just embed the JSON string right into the sourcecode. This works because JSON is valid Javascript code for an object literal. In Java, this would look something like this:
scriptCode.append("var content = " + arrayAsJsonString + ";\n");
Ok problem solved. This was how I did it:
Instead of returning a Java Array I returned a JSON object in my method.
This JSON Object has a name and several other fields per ex:
(I'm getting my data from a Java List, so I iterate the list to populate the JSON object)
SONObject jsonObj = new JSONObject();
jsonObj.clear();
for (int tt=0; tamanho>tt ; tt++) {
try {
jsonObj.put("aa"+tt, ListaJobStats.get(tt).getName());
jsonObj.put("bb"+tt , new BigDecimal(ListaJobStats.get(tt).getAge() ....
After this if I printOut the JSON object in java i get a string:
aa0: '1st name'; aa1: ' 2nd name' ; bb0: 'age'; bb1: '2nd age' ... etc etc
After this in Javascript i get my JSON Object thorugh JSF like this:
var content=#{JAVACLASS.METHODTHATRETURNSJSON};
I stringify this object in JS:
var pars= JSON.stringify(content);
and i create the JSON object
var json = JSON.parse(pars)
Now I Iterate this JSON object in JS like this:
for (var tt=0; tamanho>tt ; tt++) {
[now im specifically adding the values to create a graphic but its just na exemple how u can acess te object]
data.setValue(tt, 0, json["aa"+tt]);
data.setValue(tt, 1, json["bb"+tt]);
...
Hope it will be useful. Take care
Im brand new to Android Application development and I am working on an application that will get an RSS feed from a specific url that returns JSON data , what I am wondering is what is the best way to translate this from JSON to populate the list ,
I was thinking of making objects to hold the individual posts and then create a list of them from the json but is this the best way it seems a little rough
Just looking for idea on how others perform this action
May also be helpful to other beginners as no concrete reference base is around for this subject.
thanks chris
Very basic example:
String resultString = "{"name":"Fred Nurke", "age":"56"}";
JSONObject jobj = new JSONObject(resultString); /*This converts the string
into members of the JSON Object which
you can then manipulate*/
Log.d(jobj.getString("name")+ " is " + jobj.getString("age") + " years old");
As I said that is a very basic example of working with JSON in Android. What you'll probably be dealing with is not just a JSONObject, but a JSONArray, which as the name implies is a special Array class of JSONObjects.
Working with a JSONArray can be done as follows: (Assume we've filled the resultString already)
JSONArray jsonArr = new JSONArray(resultString);
JSONObject jsonobj;
for(int i = 0; i < jsonArr.length(); i++){
jsonobj = JSONArray.getJSONObject(i);
}
Once you have your JSONObject you can start working with it in the same manner as above.
Hope that helps.
The android API has built in support for handling JSON data which is helpful for parsing. It uses the classes shown here:
http://www.json.org/java/
API reference from android here: http://developer.android.com/reference/org/json/JSONObject.html
At a high level, You can create a JSONObject by simply passing the entire JSON string into its constructor. From there it offers a list of get methods to pull primitive types, strings, or nested JSON objects out.
If you want to keep the posts saved, I would still parse the JSON data into an object for storage, otherwise you could just create a list from the data returned directly from the JSON objects.
Is there a way in Java/J2ME to convert a string, such as:
{name:"MyNode", width:200, height:100}
to an internal Object representation of the same, in one line of code?
Because the current method is too tedious:
Object n = create("new");
setString(p, "name", "MyNode");
setInteger(p, "width", 200);
setInteger(p, "height", 100);
Maybe a JSON library?
I used a few of them and my favorite is,
http://code.google.com/p/json-simple/
The library is very small so it's perfect for J2ME.
You can parse JSON into Java object in one line like this,
JSONObject json = (JSONObject)new JSONParser().parse("{\"name\":\"MyNode\", \"width\":200, \"height\":100}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("width"));
The simplest option is Jackson:
MyObject ob = new ObjectMapper().readValue(jsonString, MyObject.class);
There are other similarly simple to use libraries (Gson was already mentioned); but some choices are more laborious, like original org.json library, which requires you to create intermediate "JSONObject" even if you have no need for those.
GSON is a good option to convert java object to json object and vise versa.
It is a tool provided by google.
for converting json to java object use: fromJson(jsonObject,javaclassname.class)
for converting java object to json object use: toJson(javaObject)
and rest will be done automatically
For more information and for download
You can do this easily with Google GSON.
Let's say you have a class called User with the fields user, width, and height and you want to convert the following json string to the User object.
{"name":"MyNode", "width":200, "height":100}
You can easily do so, without having to cast (keeping nimcap's comment in mind ;) ), with the following code:
Gson gson = new Gson();
final User user = gson.fromJson(jsonString, User.class);
Where jsonString is the above JSON String.
For more information, please look into https://code.google.com/p/google-gson/
You have many JSON parsers for Java:
JSONObject.java
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONArray.java
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONStringer.java
A JSONStringer is a tool for rapidly producing JSON text.
JSONWriter.java
A JSONWriter is a tool for rapidly writing JSON text to streams.
JSONTokener.java
A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and JSONArray constructors to parse JSON source strings.
JSONException.java
A JSONException is thrown when a syntax or procedural error is detected.
JSONString.java
The JSONString is an interface that allows classes to implement their JSON serialization.
JSON official site is where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-lib which is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.
If you click the html links there you can find anything you want.
In short:
to create a json object and a json array, the code is:
JSONObject obj = new JSONObject();
obj.put("variable1", o1);
obj.put("variable2", o2);
JSONArray array = new JSONArray();
array.put(obj);
o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.
The reverse process is fairly simple, I mean converting a string to json object/array.
String myString;
JSONObject obj = new JSONObject(myString);
JSONArray array = new JSONArray(myString);
In order to be correctly parsed you just have to know if you are parsing an array or an object.
Use google GSON library for this
public static <T> T getObject(final String jsonString, final Class<T> objectClass) {
Gson gson = new Gson();
return gson.fromJson(jsonString, objectClass);
}
http://iandjava.blogspot.in/2014/01/java-object-to-json-and-json-to-java.html
Like many stated already, A pretty simple way to do this using JSON.simple as below
import org.json.JSONObject;
String someJsonString = "{name:"MyNode", width:200, height:100}";
JSONObject jsonObj = new JSONObject(someJsonString);
And then use jsonObj to deal with JSON Object. e.g jsonObj.get("name");
As per the below link, JSON.simple is showing constant efficiency for both small and large JSON files
http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
JSON IO is by far the easiest way to convert a JSON string or JSON input stream to a Java Object
String to Java Object
Object obj = JsonReader.jsonToJava("[\"Hello, World\"]");
https://code.google.com/p/json-io/
This is an old question and json-simple (https://code.google.com/p/json-simple/) could be a good solution at that time, but please consider that project seems not to be active for a while !
I suggest the Gson which is now hosted at: https://github.com/google/gson
If performance is your issue you can have a look at some benchmarks http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/ which compare.
Apart from www.json.org you can also implement your own parser using javacc and matching your personnal grammar/schema.
See this note on my blog : http://plindenbaum.blogspot.com/2008/07/parsing-json-with-javacc-my-notebook.html
I've written a library that uses json.org to parse JSON, but it will actually create a proxy of an interface for you. The code/JAR is on code.google.com.
http://fixjures.googlecode.com/
I don't know if it works on J2ME. Since it uses Java Reflection to create proxies, I'm thinking it won't work. Also, it's currently got a hard dependency on Google Collections which I want to remove and it's probably too heavyweight for your needs, but it allows you to interact with your JSON data in the way you're looking for:
interface Foo {
String getName();
int getWidth();
int getHeight();
}
Foo myFoo = Fixjure.of(Foo.class).from(JSONSource.newJsonString("{ name : \"foo name\" }")).create();
String name = myFoo.getName(); // name now .equals("foo name");
Just make a Json object in java with the following Json String.In your case
{name:"MyNode", width:200, height:100}
if the above is your Json string , just create a Json Object with it.
JsonString ="{name:"MyNode", width:200, height:100}";
JSONObject yourJsonObject = new JSONObject(JsonString);
System.out.println("name=" + yourJsonObject.getString("name"));
System.out.println("width=" + yourJsonObject.getString("width"));
Jackson for big files, GSON for small files, and JSON.simple for handling both.