How to convert jsonString to JSONObject in Java

前端 未结 19 2999
一生所求
一生所求 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条回答
  • 2020-11-22 01:24

    Java 7 solution

    import javax.json.*;
    
    ...
    
    String TEXT;
    JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()
    

    ;

    0 讨论(0)
  • 2020-11-22 01:24

    you must import org.json

    JSONObject jsonObj = null;
            try {
                jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
    0 讨论(0)
  • 2020-11-22 01:26

    Using org.json

    If you have a String containing JSON format text, then you can get JSON Object by following steps:

    String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
    JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

    Now to access the phonetype

    Sysout.out.println(jsonObject.getString("phonetype"));
    
    0 讨论(0)
  • 2020-11-22 01:27

    To anyone still looking for an answer:

    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(stringToParse);
    
    0 讨论(0)
  • 2020-11-22 01:27

    If you are using http://json-lib.sourceforge.net (net.sf.json.JSONObject)

    it is pretty easy:

    String myJsonString;
    JSONObject json = JSONObject.fromObject(myJsonString);
    

    or

    JSONObject json = JSONSerializer.toJSON(myJsonString);
    

    get the values then with json.getString(param), json.getInt(param) and so on.

    0 讨论(0)
  • 2020-11-22 01:28

    Better Go with more simpler way by using org.json lib. Just do a very simple approach as below:

    JSONObject obj = new JSONObject();
    obj.put("phonetype", "N95");
    obj.put("cat", "WP");
    

    Now obj is your converted JSONObject form of your respective String. This is in case if you have name-value pairs.

    For a string you can directly pass to the constructor of JSONObject. If it'll be a valid json String, then okay otherwise it'll throw an exception.

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