How to convert Java Object to JSON string? - java

Hello i'm trying to convert my Java Object to a Json string to use in my view with javascript functions.
I tried to use Google's gson lib:
String myjson = "";
Gson gson = new Gson();
myjson = gson.toJson(myuser);//myuser is my java object
However when i call myjson, it consists of '"' instead of the character '"' for this reason i can't able to use it in my view, it is creating me problems.
How can I fix this, how can I create Json string properly?
Edit : Is there a chance of making a mistake while rendering the myjson?
Edit2: To reach the result of myjson in view, i'm doing
render(myjson);
at the end of my code.
Edit3: Play framework has a method of renderJSON(). However i can't use it since i'm rendering not only myjson and some other elements too.

Note that "&quot" is "Proper" JSON, so your javascript can be escaped properly, anyways if you dont want to use entities in you JSON perhaps you want to disable html formatting/escaping.
Try using
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Check the GSONBuilder Object Documentation http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html

I think he's protecting you against html special chars.
Try something like that:
Gson gson = new Gson();
String target = "my text";
String json = gson.toJson(target);
This code is extract from http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html (the api).

Related

Java parsing from escaped json string

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.

How to obtain all the matches using a regex in java [duplicate]

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.

Looking for a less verbose way to parse JSON in Android (Java)

I'm writing an app that uses JSON (from a Kimonolabs API) and while I was able to utilize my API effortlessly in Python as such:
results = json.loads(urllib.request.urlopen(KimonoAPIlink).read().decode('utf-8'))
Which returns a useable JSON dictionary:
title = results['results']['suart'][0]['stitle']['text']
href = results['results']['suart'][0]['stitle']['href']
In Java (Android specifically) I have to do it this way (Using Gson):
URL url = new URL(KimonoAPIlink);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
JsonElement x = rootobj.getAsJsonObject("results").getAsJsonArray("suart").get(0);
JsonObject y = x.getAsJsonObject();
title.setText(y.getAsJsonObject("stitle").getAsJsonPrimitive("text").toString().replace("\"", "").replace("\\","\""));
Is there any way to do this that isn't so verbose and complicated? (my code works, I'd just like it to be more simple and clean)
Moreover, can I somehow parse the whole nested JSON object into something useful (like python does) and not reparse it each layer I access?
Thanks in advance.
Edit: I've also seen people use Apache commons.io on here for this, but I don't think it returns a different JSON object (i.e. I'd still have to parse every layer)
Check out GSON, Jackson or Moshi
What you are looking for is lookup using JsonPath, wherein JSON coordinates are represented by a string with syntax pretty similar to the one you are using in Python (as well as other featuress).
For example, in your case it would be $.results.suart[o].stitle.text.
A quick look in the docs and the gson github shows it is not implemented in gson, although the JsonReader class does support a method to return that value.
There is a library implementation JsonPath in java (called JsonPath). Here's a one line code for your case (ignoring connection detail):
String result = JsonPath.parse("[some json]").read("$.results.suart[o].stitle.text");

Decode json object to string android

I used json_encode(); to convert string to json in php and then response it to android but I can't use the response, how can I convert the json to string?
when I display the response it shows this :
"{\n'OK': \n[\n{\n'Name': 'MyName',\n'Gender':'Male'\n}\n]\n}"
what shall I do?
thank you
Since you're just converting a string to json, you're not returning a JSONObject or JSONArray, according to: http://php.net/manual/en/function.json-decode.php
If you must return a string, you may have to use some json library or write your own parser.
If that doesn't sound appealing, I recommending returning a JSONObject or JSONArray with one element.
For example:
php
echo json_encode( array('result' => 'the string you are encoding') );
java
JSONObject json = new JSONObject( encodedStringResponseFromPhp );
String theStringYouEncoded = (String) json.get( "result" );
You'll need to add a throws JSONException to the function you add this java code too or put it inside a try catch block.
Have you tried using a JSON-Library like https://code.google.com/p/json-simple/? Looks like you need some help decoding the string.
Edit: You should use the json2.js library from Douglas Crockford. It provides some extra features and better/older browser support.
Read more...

Convert a JSON string to object in Java ME?

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.

Categories