我有一个名为jsonString的字符串变量:

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

现在我想把它转换成JSON对象。我在谷歌上搜索了更多,但没有得到任何预期的答案!


当前回答

使用org.json.simple.JSONObject将String转换为Json对象

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

其他回答

你可以使用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"}

资源:

谷歌Gson项目首页

Gson用户指南

例子

必须导入org.json

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

java7解决方案

import javax.json.*;

...

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

;

使用fastxmljsonnode进行通用Json解析。它在内部为所有输入创建键值的Map。

例子:

private void test(@RequestBody JsonNode node)

输入字符串:

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

用于设置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