I want a serialized JSON string to be treated simply as a string in my JSON when reading it using Jackson. When I simply escape the serialized JSON string and use it as a value, the serialized string gets treated as part of the JSON and parsed. Any ideas as to how to go about doing this?
For example:
"{\"payload\":\"{id:\"some-random-id\",version:554471325}\"}"
I would like this to be read in memory something like the following:
{ payload: "{id:\"some-random-id\",version:554471325}" }
However, the parser is trying to read the serialized string as JSON and turn it into the following:
{ payload: {id:"some-random-id", version:554471325} }
Note the difference between the two outputs. In one case, the value associated with payload is a string, in the other it's a JSON object. I'm trying to get the former, what I'm getting instead is an attempt at the latter.
Valid JSON is "set of name/value pairs", so what are you missing is the name field, and it's the reason why it's beiing parsed.
For example if the JSON is:
{"data": "{\"payload\":\"{id:\"some-random-id\",version:554471325}\"}"}
the value of data is not going to be parsed.
Btw. the JSON in payload contains key names without quotes (should probably be {"id": 123, "version": 456})
UPDATE: Answer replaced because question changed.
The examples in the question are not valid JSON. To see what it should be, let's generate it as nested JSON strings:
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> payloadObj = Map.of("id", "some-random-id", "version", 554471325);
String payloadJson = objectMapper.writeValueAsString(payloadObj);
System.out.println(payloadJson);
Map<String, Object> rootObj = Map.of("payload", payloadJson);
String rootJson = objectMapper.writeValueAsString(rootObj);
System.out.println(rootJson);
String rootString = objectMapper.writeValueAsString(rootJson);
System.out.println(rootString);
Output
{"id":"some-random-id","version":554471325}
{"payload":"{\"id\":\"some-random-id\",\"version\":554471325}"}
"{\"payload\":\"{\\\"id\\\":\\\"some-random-id\\\",\\\"version\\\":554471325}\"}"
The third line of output is what should have been the text of the first block in the question.
"{\"payload\":\"{id:\"some-random-id\",version:554471325}\"}"
But as you can see, that text is lacking many double-quotes and backslashes, so it is not valid nested JSON strings, so you can't expect a JSON parser to parse it.
JSON parsers are often lenient, and will do its best to parse it anyway, but don't blame the parser if it gets it wrong. Blame the original text and fix that, rather than trying to parse bad JSON.
Original Answer
Keys are supposed to be names, or numbers, not entire complex objects, but if you want a JSON as the key in another JSON, just invoke the JSON serializer twice.
Example
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> data1 = Map.of("foo", 42, "bar", List.of(1, 1, 2, 3, 5, 8));
String json1 = objectMapper.writeValueAsString(data1);
System.out.println(json1);
Map<String, Object> data2 = Map.of("Test", "Hello World", json1, 3.14, "End", "Now!");
String json2 = objectMapper.writeValueAsString(data2);
System.out.println(json2);
Note: Map.of() and List.of() are Java 9+
Output
{"foo":42,"bar":[1,1,2,3,5,8]}
{"{\"foo\":42,\"bar\":[1,1,2,3,5,8]}":3.14,"Test":"Hello World","End":"Now!"}
I know this is a terribly worded question, and I apologize for that. However, I can't come up with a better way of wording it and I'm unable to supply code. For anyone who stumbles on this and understands what I'm asking, I found a workaround.
I encoded the serialized JSON string to base64 so it was detected by Jackson as a string rather than a JSON object.
The example in the question above becomes:
"{\"payload\":\"e2lkOiJhbnktZXhlY3V...\"}"
where e2lkOiJhbnktZXhlY3V... is a base64 encoded representation of the string "{id:\"some-random-id\",version:554471325}"
Related
There are many threads related to this, but I can't solve my issue.
I get this string from parsing an iterable using GSON.
Iterable<ParametrosProveedores> proveedoresList;
proveedoresList = proveedoresRepository.findAll(); //From spring repository
String jsonString = gson.toJson(proveedoresList);
jsonString value is:
[{\"id\":1,\"proveedor\":\"CALIXTA\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"todas\",\"plazasNo\":\"\",\"turnoUnaVia\":false,\"turnoDosVias\":false},{\"id\":2,\"proveedor\":\"MOVILE\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"51,52\",\"plazasNo\":\"\",\"turnoUnaVia\":false,\"turnoDosVias\":false},{\"id\":3,\"proveedor\":\"TWILIO\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"todas\",\"plazasNo\":\"51\",\"turnoUnaVia\":false,\"turnoDosVias\":false},{\"id\":4,\"proveedor\":\"OTRO\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"todas\",\"plazasNo\":\"\",\"turnoUnaVia\":false,\"turnoDosVias\":false}]
Which is a json array. Is there really no way to parse from that string without removing escapes manually?
All I want to do is:
JSONArray jsonArray = parseFrom(jsonString);
Is it possible?
Since you are using a generic in the form of an Iterable<T>, you may need to use:
String jsonString = gson.toJson(proveedoresList, typeOfSrc);
Where typeOfSrc is the type of your proveedoresList. that way gson knows how to serialize the object properly.
I am trying to convert Json String into Java Object. It is working for other inputs just for one input its not working. Is their any other way to do this?
My code:
JsonParser parser=new JsonParser();
JsonObject sel=parser.parse(selectedTerritory).getAsJsonObject();
TmsMapItBuilderBean dataSet = new Gson().fromJson(sel, TmsMapItBuilderBean.class);
ArrayList dataList = dataSet.getResultList();
resultMapData = mapServiceDelegate.processAssetDataWithGeoCodeForTerritories(subId, dataList);
It shows the following error:
Error on json convert to object :com.google.gson.JsonSyntaxException:
com.google.gson.stream.MalformedJsonException: Unterminated object near
ddress' :'2500 LEE'S CHAPEL RD', "stat
Your JSON is broken. You use a character that delimits the field's with which you are encoding your object. Use an escape to encode ' as a string.
Example:
{ 'name': 'tom\'s Hut' }
However as someone pointed out ' are not meant to be used for JSON Objects. I highly encourage you to use double-quotes.
{"name": "tom's Hut"}
Would be the correct way...
For more information on JSONs see: http://www.json.org/
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.
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);
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.