Convert a JSON string to object in Java ME?
Asked Answered
D

14

118

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?

Dimorph answered 8/9, 2009 at 18:31 Comment(5)
Your string isn't really a Json object, see the Json standard... It is more like JavaScript notation.Hotfoot
@Jeremy Rudd: Should be {"name":"MyNode", "width":200, "height":100}Lyndell
@voyager: I know, but JavaScript natively supports property names without quotes.Dimorph
@PhiLho: I know that, but I kept it this way for the sake of clarity. The SO syntax highlighter would have messed it up. Name and value in red.Dimorph
Is there a way to do the conversion using Java's core APIs? Perhaps in Java 8? Java 9?Lo
C
112

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"));
Cimabue answered 8/9, 2009 at 20:12 Comment(4)
Can I use this library in an applet. If it uses Reflection then I'm going to be faced with a reflectpermission error. Would it work?Anisette
Does jsonSimple still have the JSONParser class? I can't call the class.Oxyacetylene
JSONParser is now deprecated.Yardarm
This helped me tremendously, Thanks.Saintpierre
U
81

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.

Undertow answered 1/5, 2012 at 4:56 Comment(5)
Jackson does not support J2MELomax
True, if j2me is still roughly at JDK 1.4 level (Jackson requires 1.5)Undertow
You've only got 2 upticks but deserves more. Jackson was really easy to plugin to our app. Thanks for recommending.Cryptozoic
Jackson can also deserialize to a plain object. eg. Object obj = new ObjectMapper().readValue("[1, 2, 3]", Object.class);Jacklin
More code examples using Jackson: mkyong.com/java/how-to-convert-java-object-to-from-json-jacksonCrowboot
J
61

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

Jumpoff answered 20/11, 2009 at 12:30 Comment(1)
+1 I was looking for something similar and this fits the bill perfectly!Lambent
L
23

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/

Loveliesbleeding answered 7/10, 2013 at 22:2 Comment(1)
And yes, I realize the question was asked 4 years ago, but my answer is for the interested parties needing to do this at the present :) Hope it helps someone!Loveliesbleeding
G
22

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.

Geld answered 8/9, 2009 at 18:32 Comment(5)
If J2ME has java.io.IOException; java.io.Writer; java.lang.reflect.Field; java.lang.reflect.Modifier; java.lang.reflect.Method; java.util.Collection; java.util.HashMap; java.util.Iterator; java.util.Map; java.util.TreeSet;, then you could use the first one, as they are simple java classes.Lyndell
I think there is no java.lang.reflect package in MIDP 2.0. Will make hard to make a generic parser...Hotfoot
Smart guy, voyager, you've just copied in the standard Java JSON classes' documentation.Dimorph
@Jeremy Rudd: off course I did, how did you think that I did it so fast? It wasn't an attempt to troll you, its standard practice to both link and copy. I'm sorry if it came out that way.Lyndell
I downvoted this because it doesn't answer the question. Its giving a list of related classes but none of them actually accomplish what the asker wants.Dustheap
S
7

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.

Schlenger answered 6/3, 2011 at 9:45 Comment(0)
O
7

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

Oval answered 14/1, 2014 at 9:57 Comment(0)
D
5

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/

Deanedeaner answered 2/11, 2015 at 5:29 Comment(2)
You wrote that many already stated the suggestion you posted. What's the essence of your answer?Ingemar
@Ingemar Thanks for your comments. The essence of this question was to give an one line of code which do the purpose. And since there are many apis available to do this I just wanted to give some additional info about the comparison of the efficiency of the apis too. So the essence of this answer which I meant was to give the code + some info about the comparison of efficiencies of the different apis mentioned by other fellows in this thread.Deanedeaner
N
3

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/

Nestling answered 23/10, 2013 at 23:16 Comment(0)
M
3

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.

Marcy answered 13/10, 2015 at 13:33 Comment(0)
I
2

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

Incapacity answered 8/9, 2009 at 18:41 Comment(2)
Wow. I bet that's easy and fun.Dimorph
Too bad we don't have "Funny" and "Insightful" badges to give :)Undertow
C
2

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");
Calore answered 8/9, 2009 at 20:31 Comment(1)
Amazing, though I don't want Foo, just the native Object.Dimorph
N
2

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"));
Nicolas answered 2/9, 2015 at 13:40 Comment(0)
G
2

Jackson for big files, GSON for small files, and JSON.simple for handling both.

Glomerulus answered 28/1, 2016 at 16:40 Comment(2)
evidence to back up @thanga's comment from here blog.takipi.com/…Vise
I've seen that before too, but also consider that small files are fast to parse anyway. I would only think about JSON.simple if you have a TON of small files to parse where that 30% or so difference over Jackson is going to add up. Also see the top comments there, that benchmark may not be too reliable. Really, if speed is that important to you, you should probably design so you can inject a parser to change implementations easily, and do your own benchmark tests.Lashing

© 2022 - 2024 — McMap. All rights reserved.