How to convert jsonString to JSONObject in Java

JavaArraysJsonParsing

Java Problem Overview


I have String variable called jsonString:

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

Now I want to convert it into JSON Object. I searched more on Google but didn't get any expected answers!

Java Solutions


Solution 1 - Java

Using org.json library:

try {
     JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
     Log.d("Error", err.toString());
}
    

Solution 2 - Java

To anyone still looking for an answer:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);

Solution 3 - Java

You can use google-gson. Details:

Object Examples

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

(Serialization)

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 
==> json is {"value1":1,"value2":"abc"}

Note that you can not serialize objects with circular references since that will result in infinite recursion.

(Deserialization)

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  
==> obj2 is just like obj

Another example for Gson:

Gson is easy to learn and implement, you need to know is the following two methods:

-> toJson() – convert java object to JSON format

-> fromJson() – convert JSON into java object

import com.google.gson.Gson;

public class TestObjectToJson {
  private int data1 = 100;
  private String data2 = "hello";

  public static void main(String[] args) {
      TestObjectToJson obj = new TestObjectToJson();
      Gson gson = new Gson();

      //convert java object to JSON format
      String json = gson.toJson(obj);

      System.out.println(json);
  }

}

Output

{"data1":100,"data2":"hello"}

Resources:

Google Gson Project Home Page

Gson User Guide

Example

Solution 4 - Java

Solution 5 - Java

Java 7 solution

import javax.json.*;

...

String TEXT;
JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()

;

Solution 6 - Java

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

Eg:

JSONObject jsonObj = new JSONObject("your string");

Solution 7 - Java

String to JSON using Jackson with com.fasterxml.jackson.databind:

Assuming your json-string represents as this: jsonString = {"phonetype":"N95","cat":"WP"}

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * Simple code exmpl
 */
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();

Solution 8 - Java

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.

Solution 9 - Java

you must import org.json

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

Solution 10 - Java

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

Solution 11 - Java

> Converting String to Json Object by using org.json.simple.JSONObject

private static JSONObject createJSONObject(String jsonString){
	JSONObject  jsonObject=new JSONObject();
	JSONParser jsonParser=new  JSONParser();
	if ((jsonString != null) && !(jsonString.isEmpty())) {
		try {
			jsonObject=(JSONObject) jsonParser.parse(jsonString);
		} catch (org.json.simple.parser.ParseException e) {
			e.printStackTrace();
		}
	}
	return jsonObject;
}

Solution 12 - Java

Those who didn't find solution from posted answers because of deprecation issues, you can use JsonParser from com.google.gson.

Example:

JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(jsonObject.get("phonetype"));
System.out.println(jsonObject.get("cat"));

Solution 13 - Java

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.

Solution 14 - Java

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);

Solution 15 - Java

Use JsonNode of fasterxml for the Generic Json Parsing. It internally creates a Map of key value for all the inputs.

Example:

private void test(@RequestBody JsonNode node)

input String :

{"a":"b","c":"d"}

Solution 16 - Java

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(

Solution 17 - Java

NOTE that GSON with deserializing an interface will result in exception like below.

"java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."

While deserialize; GSON don't know which object has to be intantiated for that interface.

This is resolved somehow here.

However FlexJSON has this solution inherently. while serialize time it is adding class name as part of json like below.

{
    "HTTPStatus": "OK",
    "class": "com.XXX.YYY.HTTPViewResponse",
    "code": null,
    "outputContext": {
        "class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
        "eligible": true
    }
}

So JSON will be cumber some; but you don't need write InstanceCreator which is required in GSON.

Solution 18 - Java

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"));

Solution 19 - Java

For setting json single object to list ie

"locations":{

}

in to List<Location>

use

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

jackson.mapper-asl-1.9.7.jar

Solution 20 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMr. Sajid ShaikhView Question on Stackoverflow
Solution 1 - JavadogbaneView Answer on Stackoverflow
Solution 2 - JavaMappanView Answer on Stackoverflow
Solution 3 - JavakamaciView Answer on Stackoverflow
Solution 4 - JavaT.J. CrowderView Answer on Stackoverflow
Solution 5 - JavaRSGView Answer on Stackoverflow
Solution 6 - JavaCharuView Answer on Stackoverflow
Solution 7 - JavaYugertenView Answer on Stackoverflow
Solution 8 - JavaGubatronView Answer on Stackoverflow
Solution 9 - JavaCabezasView Answer on Stackoverflow
Solution 10 - JavaPanini LuncherView Answer on Stackoverflow
Solution 11 - JavaAnzar AnsariView Answer on Stackoverflow
Solution 12 - JavaChintan PatelView Answer on Stackoverflow
Solution 13 - JavaTheroView Answer on Stackoverflow
Solution 14 - JavaAravind CheekkallurView Answer on Stackoverflow
Solution 15 - JavaVishnu View Answer on Stackoverflow
Solution 16 - JavaNatesh bhatView Answer on Stackoverflow
Solution 17 - JavaKanagavelu SugumarView Answer on Stackoverflow
Solution 18 - JavaAzhar ZafarView Answer on Stackoverflow
Solution 19 - Javauser3012570View Answer on Stackoverflow
Solution 20 - JavaTheLittleNarutoView Answer on Stackoverflow