Rectangle 27 404

JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");

I tried with like that JSONObject js=new JSONObject(jsonstring); but it shows error. on jsonstring

he got an error because he's not using org.json, he's using google-gson which doesn't work that way.

@Gubatron Thanks dude you are right i have just downloaded it and make jar so now its working fine.

@dogbane What if I don't know the structure of the string. More clearly, how can I convert a Dynamic generated jsonString to jsonObject?

JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 403

JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");

I tried with like that JSONObject js=new JSONObject(jsonstring); but it shows error. on jsonstring

he got an error because he's not using org.json, he's using google-gson which doesn't work that way.

@Gubatron Thanks dude you are right i have just downloaded it and make jar so now its working fine.

@dogbane What if I don't know the structure of the string. More clearly, how can I convert a Dynamic generated jsonString to jsonObject?

JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 94

To anyone still looking for an answer:

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

And can you please mention which package to import for the same?

import org.json.simple.JSONObject

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.

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: github.com/fabienrenaud/java-json-benchmark It clearly shows jackson faster than anything else and 5 to 6 times faster than org.json.

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 94

To anyone still looking for an answer:

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

And can you please mention which package to import for the same?

import org.json.simple.JSONObject

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.

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: github.com/fabienrenaud/java-json-benchmark It clearly shows jackson faster than anything else and 5 to 6 times faster than org.json.

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 3

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

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

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 3

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

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

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 33

You can use google-gson. Details:

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}
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.

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

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

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

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

@T.J. Crowder thanks. I will remove the client part too.

+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.

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 33

You can use google-gson. Details:

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}
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.

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

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

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

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

@T.J. Crowder thanks. I will remove the client part too.

+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.

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 27

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

As of this writing, there are these 20:

...but of course the list can change.

hey hi i didnt find in it can you give me link

@Sajid: The "JSON home page" was the link. They're actually listed on that page, near the bottom. (It's pretty subtle, I guess, because there's no heading or anything.) I've added a list of the ones that are currently there (just because StackOverflow should mostly stand-alone), but of course the JSON page is the definitive list going forward.

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 27

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

As of this writing, there are these 20:

...but of course the list can change.

hey hi i didnt find in it can you give me link

@Sajid: The "JSON home page" was the link. They're actually listed on that page, near the bottom. (It's pretty subtle, I guess, because there's no heading or anything.) I've added a list of the ones that are currently there (just because StackOverflow should mostly stand-alone), but of course the JSON page is the definitive list going forward.

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 16

import javax.json.*;

...

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

This library has the worst performance of them all. See this benchmark I did with JMH: github.com/fabienrenaud/java-json-benchmark

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 16

import javax.json.*;

...

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

This library has the worst performance of them all. See this benchmark I did with JMH: github.com/fabienrenaud/java-json-benchmark

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 2

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

What is JSONParser? Is it only part of Contacts Provider?

@IgorGanapolsky JSONParser is a buit in option provided by simple JSON. To do this, include json-simple-1.1.1.jar

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 2

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

What is JSONParser? Is it only part of Contacts Provider?

@IgorGanapolsky JSONParser is a buit in option provided by simple JSON. To do this, include json-simple-1.1.1.jar

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 7

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.

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.

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 7

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.

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.

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 4

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

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

JSONObject json = JSONSerializer.toJSON(myJsonString); will produce an erroe of Type mismatch the other one works

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 4

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

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

JSONObject json = JSONSerializer.toJSON(myJsonString); will produce an erroe of Type mismatch the other one works

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 3

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

private void test(@RequestBody JsonNode node)
{"a":"b","c":"d"}

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject
Rectangle 27 3

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

arrays - How to convert String to JSONObject in Java - Stack Overflow

java arrays json parsing jsonobject