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
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/
Jackson for big files, GSON for small files, and JSON.simple for handling both.
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.
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/
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