如何在Java中将jsonString转换为JSONObject

我有一个名为jsonString String变量:

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

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

使用org.json库:

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

对于仍在寻找答案的人:

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

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

对象示例

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

请注意,您不能使用循环引用序列化对象,因为这将导致无限递归。

(反序列化)

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

Gson的另一个例子:

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

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

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

产量

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

资源:

Google Gson Project主页

Gson用户指南

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

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

  • org.json
  • org.json.me
  • jacksonJSON处理器
  • JSON-LIB
  • JSON工具
  • JSON-简单
  • Stringtree
  • SOJO
  • 的Restlet
  • 抛弃
  • JSON-标签库
  • XStream的
  • JsonMarshaller
  • Flexjson
  • JON工具
  • 谷歌,GSON
  • 阿尔戈
  • jsonij
  • FASTJSON

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

Java 7解决方案

 import javax.json.*; ... String TEXT; JsonObject body = Json.createReader(new StringReader(TEXT)).readObject() 

;

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

在这种情况下,我有一个类将对应于您的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); ... 

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

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

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

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

 JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}"); System.out.println(jsonObject.getString("phonetype")); 

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

你必须导入org.json

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

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

例如:

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

如果您使用的是http://json-lib.sourceforge.net (net.sf.json.JSONObject)

这很简单:

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

要么

 JSONObject json = JSONSerializer.toJSON(myJsonString); 

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

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

例:

 private void test(@RequestBody JsonNode node) 

输入字符串:

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

将字符串转换为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); 

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

 "locations":{ } 

List

使用

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

jackson.mapper-ASL-1.9.7.jar

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

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

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

这在某种程度上得到了解决。

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

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

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

无需使用任何外部库。

你可以使用这个类:) (处理偶数列表,嵌套列表和json)

 public class Utility { public static Map 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 _jsonToMap_(JSONObject json) throws JSONException { Map retMap = new HashMap(); if(json != JSONObject.NULL) { retMap = toMap(json); } return retMap; } private static Map toMap(JSONObject object) throws JSONException { Map map = new HashMap(); Iterator 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 toList(JSONArray array) throws JSONException { List list = new ArrayList(); 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; } } 

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

 HashMap hashMap = new HashMap<>(Utility.jsonToMap( 

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

 JSONObject obj = new JSONObject(); obj.put("phonetype", "N95"); obj.put("cat", "WP"); 

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

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