Convert a JSON string to object in Java ME?

前端 未结 14 915
有刺的猬
有刺的猬 2020-11-22 02:12

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

相关标签:
14条回答
  • 2020-11-22 02:48

    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

    0 讨论(0)
  • 2020-11-22 02:50

    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/

    0 讨论(0)
  • 2020-11-22 02:50

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

    0 讨论(0)
  • 2020-11-22 02:54

    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.

    0 讨论(0)
  • 2020-11-22 02:58

    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/

    0 讨论(0)
  • 2020-11-22 02:59

    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

    0 讨论(0)
提交回复
热议问题