如何在Java中将jsonString转换为JSONObject

时间:2021-08-15 19:41:47

I have String variable called jsonString:

我有一个名为jsonString的String变量:

{"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...

现在我想将其转换为JSON对象。我在Google上搜索得更多,但没有得到任何预期的答案......

15 个解决方案

#1


517  

Using org.json library:

使用org.json库:

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

#2


119  

To anyone still looking for an answer:

对于仍在寻找答案的人:

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

#3


39  

You can use google-gson. Details:

你可以使用google-gson。细节:

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的另一个例子:

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

Gson易于学习和实现,您需要知道以下两种方法:

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

- > toJson() - 将java对象转换为JSON格式

-> fromJson() – convert JSON into java object

- > fromJson() - 将JSON转换为java对象

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

Google Gson Project主页

Gson User Guide

Gson用户指南

Example

#4


28  

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

JSON主页上链接了各种Java JSON序列化程序和反序列化程序。

As of this writing, there are these 20:

在撰写本文时,有以下20个:

...but of course the list can change.

......但当然列表可以改变。

#5


21  

Java 7 solution

Java 7解决方案

import javax.json.*;

...

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

;

;

#6


9  

I like to use google-gson for this, and it's precisely because I don't need to work with JSONObject directly.

我喜欢使用google-gson,这正是因为我不需要直接使用JSONObject。

In that case I'd have a class that will correspond to the properties of your JSON Object

在这种情况下,我有一个类将对应于您的JSON对象的属性

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.

但是,我认为你的问题更像是,如何从JSON字符串中获取实际的JSONObject对象。

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.

我正在看google-json api并且找不到任何像org.json那样直接的api,如果你非常需要使用准系统JSONObject,这可能是你想要使用的。

http://www.json.org/javadoc/org/json/JSONObject.html

http://www.json.org/javadoc/org/json/JSONObject.html

With org.json.JSONObject (another completely different API) If you want to do something like...

使用org.json.JSONObject(另一个完全不同的API)如果你想做类似的事情......

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.

我认为google-gson的美妙之处在于你不需要处理JSONObject。你只需抓住json,传递类就想要反序列化,你的类属性将与JSON匹配,但是再一次,每个人都有自己的要求,也许你无法负担得到预先映射的类的奢侈反序列化的一面,因为JSON生成端的东西可能太动态了。在这种情况下,只需使用json.org。

#7


8  

you must import org.json

你必须导入org.json

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

#8


7  

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

要将String转换为JSONObject,只需将String实例传递给JSONObject的Constructor即可。

Eg:

例如:

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

#9


3  

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

如果您使用的是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.

然后使用json.getString(param),json.getInt(param)等获取值。

#10


3  

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

使用fastxml的JsonNode进行Generic Json Parsing。它在内部为所有输入创建键值的Map。

Example:

例:

private void test(@RequestBody JsonNode node)

input String :

输入字符串:

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

#11


2  

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

将字符串转换为json,sting就像json。 { “PHONETYPE”: “N95”, “猫”: “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);

#12


0  

For setting json single object to list ie

用于将json单个对象设置为列表即

"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

jackson.mapper-ASL-1.9.7.jar

#13


0  

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

请注意,使用反序列化接口的GSON将导致异常,如下所示。

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

反序列化; GSON不知道哪个对象必须为该接口实例化。

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.

但是FlexJSON本身就有这个解决方案。序列化时,它将类名作为json的一部分添加,如下所示。

{
    "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.

所以JSON会有些麻烦;但是您不需要编写GSON中需要的InstanceCreator。

#14


0  

No need to use any external library.

无需使用任何外部库。

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

你可以使用这个类:)(处理偶数列表,嵌套列表和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 :

要将JSON字符串转换为hashmap,请使用以下命令:

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(

#15


-1  

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

使用org.json lib以更简单的方式改进Go。只需做一个非常简单的方法如下:

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.

现在obj是您各自String的转换后的JSONObject形式。如果您有名称 - 值对,则会出现这种情况。

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.

对于字符串,您可以直接传递给JSONObject的构造函数。如果它是一个有效的json String,那么好吧否则它会抛出异常。

#1


517  

Using org.json library:

使用org.json库:

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

#2


119  

To anyone still looking for an answer:

对于仍在寻找答案的人:

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

#3


39  

You can use google-gson. Details:

你可以使用google-gson。细节:

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的另一个例子:

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

Gson易于学习和实现,您需要知道以下两种方法:

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

- > toJson() - 将java对象转换为JSON格式

-> fromJson() – convert JSON into java object

- > fromJson() - 将JSON转换为java对象

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

Google Gson Project主页

Gson User Guide

Gson用户指南

Example

#4


28  

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

JSON主页上链接了各种Java JSON序列化程序和反序列化程序。

As of this writing, there are these 20:

在撰写本文时,有以下20个:

...but of course the list can change.

......但当然列表可以改变。

#5


21  

Java 7 solution

Java 7解决方案

import javax.json.*;

...

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

;

;

#6


9  

I like to use google-gson for this, and it's precisely because I don't need to work with JSONObject directly.

我喜欢使用google-gson,这正是因为我不需要直接使用JSONObject。

In that case I'd have a class that will correspond to the properties of your JSON Object

在这种情况下,我有一个类将对应于您的JSON对象的属性

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.

但是,我认为你的问题更像是,如何从JSON字符串中获取实际的JSONObject对象。

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.

我正在看google-json api并且找不到任何像org.json那样直接的api,如果你非常需要使用准系统JSONObject,这可能是你想要使用的。

http://www.json.org/javadoc/org/json/JSONObject.html

http://www.json.org/javadoc/org/json/JSONObject.html

With org.json.JSONObject (another completely different API) If you want to do something like...

使用org.json.JSONObject(另一个完全不同的API)如果你想做类似的事情......

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.

我认为google-gson的美妙之处在于你不需要处理JSONObject。你只需抓住json,传递类就想要反序列化,你的类属性将与JSON匹配,但是再一次,每个人都有自己的要求,也许你无法负担得到预先映射的类的奢侈反序列化的一面,因为JSON生成端的东西可能太动态了。在这种情况下,只需使用json.org。

#7


8  

you must import org.json

你必须导入org.json

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

#8


7  

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

要将String转换为JSONObject,只需将String实例传递给JSONObject的Constructor即可。

Eg:

例如:

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

#9


3  

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

如果您使用的是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.

然后使用json.getString(param),json.getInt(param)等获取值。

#10


3  

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

使用fastxml的JsonNode进行Generic Json Parsing。它在内部为所有输入创建键值的Map。

Example:

例:

private void test(@RequestBody JsonNode node)

input String :

输入字符串:

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

#11


2  

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

将字符串转换为json,sting就像json。 { “PHONETYPE”: “N95”, “猫”: “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);

#12


0  

For setting json single object to list ie

用于将json单个对象设置为列表即

"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

jackson.mapper-ASL-1.9.7.jar

#13


0  

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

请注意,使用反序列化接口的GSON将导致异常,如下所示。

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

反序列化; GSON不知道哪个对象必须为该接口实例化。

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.

但是FlexJSON本身就有这个解决方案。序列化时,它将类名作为json的一部分添加,如下所示。

{
    "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.

所以JSON会有些麻烦;但是您不需要编写GSON中需要的InstanceCreator。

#14


0  

No need to use any external library.

无需使用任何外部库。

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

你可以使用这个类:)(处理偶数列表,嵌套列表和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 :

要将JSON字符串转换为hashmap,请使用以下命令:

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(

#15


-1  

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

使用org.json lib以更简单的方式改进Go。只需做一个非常简单的方法如下:

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.

现在obj是您各自String的转换后的JSONObject形式。如果您有名称 - 值对,则会出现这种情况。

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.

对于字符串,您可以直接传递给JSONObject的构造函数。如果它是一个有效的json String,那么好吧否则它会抛出异常。