How to convert jsonString to JSONObject in Java

前端 未结 19 3001
一生所求
一生所求 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:32

    To convert String into JSONObject you just need to pass the String instance into Constructor of JSONObject.

    Eg:

    JSONObject jsonObj = new JSONObject("your string");
    
    0 讨论(0)
  • 2020-11-22 01:33

    To convert a string to json and the sting is like json. {"phonetype":"N95","cat":"WP"}

    String Data=response.getEntity().getText().toString(); // reading the string value 
    JSONObject json = (JSONObject) new JSONParser().parse(Data);
    String x=(String) json.get("phonetype");
    System.out.println("Check Data"+x);
    String y=(String) json.get("cat");
    System.out.println("Check Data"+y);
    
    0 讨论(0)
  • 2020-11-22 01:34

    Using org.json library:

    try {
         JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
    }catch (JSONException err){
         Log.d("Error", err.toString());
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • Codehaus Jackson - I have been this awesome API since 2012 for my RESTful webservice and JUnit tests. With their API, you can:

    (1) Convert JSON String to Java bean

    public static String beanToJSONString(Object myJavaBean) throws Exception {
        ObjectMapper jacksonObjMapper = new ObjectMapper();
        return jacksonObjMapper.writeValueAsString(myJavaBean);
    }
    

    (2) Convert JSON String to JSON object (JsonNode)

    public static JsonNode stringToJSONObject(String jsonString) throws Exception {
        ObjectMapper jacksonObjMapper = new ObjectMapper();
        return jacksonObjMapper.readTree(jsonString);
    }
    
    //Example:
    String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";   
    JsonNode jsonNode = stringToJSONObject(jsonString);
    Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
    Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());
    

    (3) Convert Java bean to JSON String

        public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
        ObjectMapper jacksonObjMapper = new ObjectMapper();
        return jacksonObjMapper.readValue(JSONString, beanClass);
    }
    

    REFS:

    1. Codehaus Jackson

    2. JsonNode API - How to use, navigate, parse and evaluate values from a JsonNode object

    3. Tutorial - Simple tutorial how to use Jackson to convert JSON string to JsonNode

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

    No need to use any external library.

    You can use this class instead :) (handles even lists , nested lists and json)

    public class Utility {
    
        public static Map<String, Object> jsonToMap(Object json) throws JSONException {
    
            if(json instanceof JSONObject)
                return _jsonToMap_((JSONObject)json) ;
    
            else if (json instanceof String)
            {
                JSONObject jsonObject = new JSONObject((String)json) ;
                return _jsonToMap_(jsonObject) ;
            }
            return null ;
        }
    
    
       private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
            Map<String, Object> retMap = new HashMap<String, Object>();
    
            if(json != JSONObject.NULL) {
                retMap = toMap(json);
            }
            return retMap;
        }
    
    
        private static Map<String, Object> toMap(JSONObject object) throws JSONException {
            Map<String, Object> map = new HashMap<String, Object>();
    
            Iterator<String> keysItr = object.keys();
            while(keysItr.hasNext()) {
                String key = keysItr.next();
                Object value = object.get(key);
    
                if(value instanceof JSONArray) {
                    value = toList((JSONArray) value);
                }
    
                else if(value instanceof JSONObject) {
                    value = toMap((JSONObject) value);
                }
                map.put(key, value);
            }
            return map;
        }
    
    
        public static List<Object> toList(JSONArray array) throws JSONException {
            List<Object> list = new ArrayList<Object>();
            for(int i = 0; i < array.length(); i++) {
                Object value = array.get(i);
                if(value instanceof JSONArray) {
                    value = toList((JSONArray) value);
                }
    
                else if(value instanceof JSONObject) {
                    value = toMap((JSONObject) value);
                }
                list.add(value);
            }
            return list;
        }
    }
    

    To convert your JSON string to hashmap use this :

    HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(
    
    0 讨论(0)
提交回复
热议问题