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

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

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


当前回答

那些因为弃用问题而无法从发布的答案中找到解决方案的人,可以使用com.google.gson中的JsonParser。

例子:

JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(jsonObject.get("phonetype"));
System.out.println(jsonObject.get("cat"));

其他回答

字符串到JSON使用Jackson com.fasterxml.jackson.databind:

假设你的json-string表示如下: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();

要将String转换为JSONObject,您只需要将String实例传递到JSONObject的构造函数中。

Eg:

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

从JSON主页可以链接到各种Java JSON序列化器和反序列化器。

在撰写本文时,有22种:

JSON-java. JSONUtil. JSONP. 杰森-利布。 字符串树。 索乔。 json-taglib. Flexjson。 阿尔戈。 杰索尼。 法斯特森。 姆森。 杰森。 JSON-简单。 json-io. 谷歌-格森。 福斯新星JSON。 玉米转换器。 阿帕奇·约翰松。 根森。 库克森。 程序库。

...当然,这个名单是可以改变的。

你可以使用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用户指南

例子

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

这很简单:

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

or

JSONObject json = JSONSerializer.toJSON(myJsonString);

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