How to convert jsonString to JSONObject in Java

前端 未结 19 3242
一生所求
一生所求 2020-11-22 00:39

I have String variable called jsonString:

{\"phonetype\":\"N95\",\"cat\":\"WP\"}

Now I want to convert it into JSON Object. I

19条回答
  •  Happy的楠姐
    2020-11-22 01:34

    I like to use google-gson for this, and it's precisely because I don't need to work with JSONObject directly.

    In that case I'd have a class that will correspond to the properties of your JSON Object

    class Phone {
     public String phonetype;
     public String cat;
    }
    
    
    ...
    String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
    Gson gson = new Gson();
    Phone fooFromJson = gson.fromJson(jsonString, Phone.class);
    ...
    

    However, I think your question is more like, How do I endup with an actual JSONObject object from a JSON String.

    I was looking at the google-json api and couldn't find anything as straight forward as org.json's api which is probably what you want to be using if you're so strongly in need of using a barebones JSONObject.

    http://www.json.org/javadoc/org/json/JSONObject.html

    With org.json.JSONObject (another completely different API) If you want to do something like...

    JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
    System.out.println(jsonObject.getString("phonetype"));
    

    I think the beauty of google-gson is that you don't need to deal with JSONObject. You just grab json, pass the class to want to deserialize into, and your class attributes will be matched to the JSON, but then again, everyone has their own requirements, maybe you can't afford the luxury to have pre-mapped classes on the deserializing side because things might be too dynamic on the JSON Generating side. In that case just use json.org.

提交回复
热议问题