543

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!

Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
Mr. Sajid Shaikh
  • 7,051
  • 4
  • 21
  • 35
  • 1
    No its right, because i wanted to create json object from json string, answer given by dogbane showed right track to answer. – Mr. Sajid Shaikh Aug 20 '15 at 09:16
  • Both answers of Mappan and dogbane are correct but they are using different modules. You should be careful to import correct module for each one because there are many JSONObject modules. – Arashsoft Dec 14 '15 at 21:37
  • I tried with GSON library. Please check this [link](https://stackoverflow.com/a/44389185/1404798). – Thirumalvalavan Jun 06 '17 at 11:47
  • Here's a short video that demonstrates [how to create a JSONObject in Java using org.json.](https://www.youtube.com/watch?v=-qEpxIARKxE) – drorw Nov 13 '18 at 18:52

21 Answers21

843

Using org.json library:

try {
     JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
     Log.d("Error", err.toString());
}
Matthew Mitchell
  • 514
  • 4
  • 14
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 10
    I tried with like that JSONObject js=new JSONObject(jsonstring); but it shows error. on jsonstring – Mr. Sajid Shaikh Mar 09 '11 at 12:40
  • did you escape the quotes in your string like i did? – dogbane Mar 09 '11 at 13:13
  • 39
    he got an error because he's not using org.json, he's using google-gson which doesn't work that way. – Gubatron Mar 09 '11 at 13:20
  • 2
    @Gubatron Thanks dude you are right i have just downloaded it and make jar so now its working fine. – Mr. Sajid Shaikh Mar 10 '11 at 05:45
  • 3
    @dogbane What if I don't know the structure of the string. More clearly, how can I convert a Dynamic generated jsonString to jsonObject? – Saumyaraj Mar 20 '14 at 07:02
  • @programmer you don't need to know the structure of the string. Just pass the json string to the constructor to create a JSONObject e.g. `new JSONObject(myJsonString)` – dogbane Mar 20 '14 at 11:44
  • @dogbane But the string that I pass to the constructor must be have quotes escaped by "\", and to do that I must know the structure of the string to decide where to put "\". – Saumyaraj Mar 20 '14 at 12:54
  • @programmer you only need to escape quotes if you are creating a new java string. If you already have a json string (stored in a variable), you don't need to escape the quotes. – dogbane Mar 20 '14 at 17:43
  • @dogbane sry, but I am still not understanding. – Saumyaraj Mar 21 '14 at 05:22
  • 2
    This will cause an unhandled exception error, remember to use `try { // above code } catch (JSONException e) { // custom code }` – AndyRoid Aug 26 '14 at 03:40
  • 84
    Using google-gson you can do it like this: `JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();` – kazy May 13 '15 at 18:38
  • Try to use a regex to add the quotes, this is a simple approach and will not work on all json strings (not working for strings that contain escaped quotes in text, there should be another regex therefore): .replaceAll(".*\".*", "\\\""); JSONObject jso= new JSONObject(); – Lunero Jun 09 '15 at 19:35
  • @dogbane I am getting a error saying `constructor JSONObject(String) is undefined` – Matchendran Aug 31 '15 at 14:46
  • 1
    org.json is a proof-of-concept library. it is one of the worst in terms of performance and features. One should look at the feature set and performance of a json lib before choosing. See this benchmark I did using JMH: https://github.com/fabienrenaud/java-json-benchmark It clearly shows jackson faster than anything else and 5 to 6 times faster than org.json. – fabien Jun 27 '16 at 20:45
  • 1
    one thing i want to add if string is null it will generate exception... – LoveToCode Sep 30 '16 at 05:37
  • I'm getting `Method threw 'java.lang.RuntimeException' exception. Cannot evaluate org.json.JSONObject.toString()` when running this exact code. using org.json library. – Adam Johns Nov 08 '16 at 13:35
  • DOWNLOAD JSONObject .jar from http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm – Om Sao Jul 19 '17 at 10:38
  • Note that, depending on your classpath, (Jersey 1.19 with Genson in my case) you might also need to read the response input stream manually if you also want to read the response as a JSON String. – dvlcube Mar 03 '20 at 04:42
199

To anyone still looking for an answer:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
Mappan
  • 2,537
  • 2
  • 22
  • 27
  • 33
    And can you please mention which package to import for the same? – gonephishing Jun 18 '15 at 10:20
  • 17
    This is working for me with: `import org.json.simple.JSONObject` – Mafro34 Jul 29 '15 at 13:14
  • 2
    Version 1.1.1 of json-simple seems to have some problem. The above gives "Unhandled Exception" for `parser.parse(` and wants try-catch or throws. But when you add either one, it gives a `Unhandled exception type ParseException` error, or NoClassDefFound error for ParseException of `org.json.simple.parser` even when you have json-simple in Maven depedencies and clearly visible in the library of the project. – Juha Untinen Feb 17 '16 at 08:40
  • 4
    org.json is a proof-of-concept library. it is one of the worst in terms of performance and features. One should look at the feature set and performance of a json lib before choosing. See this benchmark I did using JMH: https://github.com/fabienrenaud/java-json-benchmark It clearly shows jackson faster than anything else and 5 to 6 times faster than org.json. – fabien Jun 27 '16 at 20:47
  • 13
    JSONParser parser = new JSONParser(); seems depricated – Ouissal Jul 09 '18 at 08:19
  • Unexpected token END OF FILE at position 0. at org.json.simple.parser.JSONParser.parse. i am getting error. – Onkar Musale Mar 13 '19 at 11:06
  • In case of Gson. JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(json).getAsJsonObject(); – Rajat Apr 09 '19 at 10:34
56

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

kamaci
  • 72,915
  • 69
  • 228
  • 366
  • *"If you are asking to process at client side it depends on your programming language. For example with Java you can use google-gson"* I think you probably meant "server" rather than "client" there. And he did tag his question "Java". – T.J. Crowder Mar 09 '11 at 12:59
  • +1. I've used Gson in 4-5 projects now, in quite different contexts, server and client side (also in Android app), and it has never failed me. Very nice & clean lib. – Jonik Oct 31 '13 at 18:21
  • If you want to use gson but don't have a pre defined POJO class (i.e. you have a generic json without a pre defined structure), this answer may help - https://stackoverflow.com/questions/4110664/gson-directly-convert-string-to-jsonobject-no-pojo – Leandro David Feb 01 '18 at 21:03
45

There are various Java JSON serializers and deserializers linked from the JSON home page.

As of this writing, there are these 22:

...but of course the list can change.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
27

Java 7 solution

import javax.json.*;

...

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

;

RSG
  • 384
  • 3
  • 7
  • 5
    This library has the worst performance of them all. See this benchmark I did with JMH: https://github.com/fabienrenaud/java-json-benchmark – fabien Jun 27 '16 at 20:47
24

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

Eg:

JSONObject jsonObj = new JSONObject("your string");
Nikolay K
  • 3,770
  • 3
  • 25
  • 37
Charu
  • 1,055
  • 13
  • 18
19

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();
Yugerten
  • 878
  • 1
  • 11
  • 30
12

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.

Gubatron
  • 6,222
  • 5
  • 35
  • 37
10

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"));
Bikram Kumar
  • 393
  • 1
  • 4
  • 15
Chintan Patel
  • 123
  • 1
  • 7
  • Worked for me. I used to parse body sting received from AWS api gateway. JsonObject request; String body = request.get("body").toString(); logger.log("body: " + body); String jsonObject = JsonParser.parseString(body).getAsString(); – Dipan Mandal May 24 '22 at 18:24
9

you must import org.json

JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
Cabezas
  • 9,329
  • 7
  • 67
  • 69
6

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

Panini Luncher
  • 639
  • 8
  • 10
6

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;
}
Anzar Ansari
  • 109
  • 1
  • 5
3

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) or/and json.getInt(param) and so on.

shluvme
  • 713
  • 7
  • 24
Thero
  • 109
  • 4
  • JSONObject json = JSONSerializer.toJSON(myJsonString); will produce an erroe of Type mismatch the other one works – Henrique C. Oct 18 '13 at 11:53
3

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);
Aravind Cheekkallur
  • 3,157
  • 6
  • 27
  • 41
3

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"}
Vishnu
  • 51
  • 2
2

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(
Natesh bhat
  • 12,274
  • 10
  • 84
  • 125
1

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

Majid Golshadi
  • 2,686
  • 2
  • 20
  • 29
1

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.

Community
  • 1
  • 1
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101
1

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"));
Azhar Zafar
  • 1,554
  • 1
  • 10
  • 13
-1

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.

TheLittleNaruto
  • 8,325
  • 4
  • 54
  • 73
-1

For someone who uses com.alibaba/fastjson, let's say more complicated data format which looks like below:

{
  "phonetype":"N95",
  "cat":"WP",
  "data":{
      "phone":"95",
      "kitty":"W"
  }

}

You can parse the data as below:

JSONObject jsonObject = JSON.parseObject(str);
String pt = jsonObject.getString("phonetype");
JSONObject d = jsonObject.getJSONObject("data");
String p = d.getString("phone");

If you wanna Getting the key and value, code sample is shown below:

for(Map.Entry<String,Object> entry : jsonObject.entrySet()){
    String key = entry.getKey();
    Object value = entry.getValue();
    System.out.println(key + ", " + value.toString());
}

The pom dependency for maven project:

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.47</version>
</dependency>
Nick Dong
  • 3,638
  • 8
  • 47
  • 84