如何将 Java 字符串转换为 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29182842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:30:58  来源:igfitidea点击:

How to convert Java String to JSON Object

javajsonorg.json

提问by Nishit

This question has been asked earlier, but I am unable to figure out the error in my code from the responses to those questions.

之前已经问过这个问题,但我无法从对这些问题的回答中找出我的代码中的错误。



I am trying to convert a java string into json object. Here is the code:

我正在尝试将 java 字符串转换为 json 对象。这是代码:

import org.json.JSONObject;
//Other lines of code
URL seatURL = new URL("http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
//Return the JSON Response from the API
BufferedReader br = new BufferedReader(new InputStreamReader(seatURL.openStream(),Charset.forName("UTF-8")));
String readAPIResponse = " ";
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
    jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString);
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

The output is:

输出是:

{"title":"Free Music Archive - Genres","message":"","errors":[],"total":"163","total_pages":82,"page":1,"limit":"2","dataset":[{"genre_id":"1","genre_parent_id":"38","genre_title":"Avant-Garde","genre_handle":"Avant-Garde","genre_color":"#006666"},{"genre_id":"2","genre_parent_id":null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
---------------------------
{}

So, as you can see, the jsonstring is getting the data, but the jsonObj does not. I am using org.json JAR.

因此,如您所见,jsonstring 正在获取数据,但 jsonObj 没有。我正在使用 org.json JAR。

采纳答案by APD

You are passing into the JSONObjectconstructor an instance of a StringBuilderclass.

您正在向JSONObject构造函数传递一个StringBuilder类的实例。

This is using the JSONObject(Object)constructor, not the JSONObject(String)one.

这是使用JSONObject(Object)构造函数,而不是构造函数JSONObject(String)

Your code should be:

你的代码应该是:

JSONObject jsonObj = new JSONObject(jsonString.toString());

回答by Ola

The string that you pass to the constructor JSONObjecthas to be escaped with quote():

您传递给构造函数的字符串JSONObject必须使用quote()以下内容进行转义:

public static java.lang.String quote(java.lang.String string)

Your code would now be:

你的代码现在是:

JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

回答by My God

Your json -

你的 json -

{
    "title":"Free Music Archive - Genres",
    "message":"",
    "errors":[
    ],
    "total":"163",
    "total_pages":82,
    "page":1,
    "limit":"2",
    "dataset":[
    {
    "genre_id":"1",
    "genre_parent_id":"38",
    "genre_title":"Avant-Garde",
    "genre_handle":"Avant-Garde",
    "genre_color":"#006666"
    },
    {
    "genre_id":"2",
    "genre_parent_id":null,
    "genre_title":"International",
    "genre_handle":"International",
    "genre_color":"#CC3300"
    }
    ]
    }

Using the JSON library from json.org-

使用来自json.org-的 JSON 库

JSONObject o = new JSONObject(jsonString);

NOTE:

笔记:

The following information will be helpful to you - json.org.

以下信息将对您有所帮助 - json.org

UPDATE:

更新:

import org.json.JSONObject;
 //Other lines of code
URL seatURL = new URL("http://freemusicarchive.org/
 api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
 //Return the JSON Response from the API
 BufferedReader br = new BufferedReader(new         
 InputStreamReader(seatURL.openStream(),
 Charset.forName("UTF-8")));
 String readAPIResponse = " ";
 StringBuilder jsonString = new StringBuilder();
 while((readAPIResponse = br.readLine()) != null){
   jsonString.append(readAPIResponse);
 }
 JSONObject jsonObj = new JSONObject(jsonString.toString());
 System.out.println(jsonString);
 System.out.println("---------------------------");
 System.out.println(jsonObj);

回答by Brooks

@Nishit, JSONObject does not natively understand how to parse through a StringBuilder; instead you appear to be using the JSONObject(java.lang.Object bean) constructor to create the JSONObject, however passing it a StringBuilder.

@Nishit,JSONObject 本身并不了解如何通过 StringBuilder 进行解析;相反,您似乎正在使用 JSONObject(java.lang.Object bean) 构造函数来创建 JSONObject,但将其传递给 StringBuilder。

See this link for more information on that particular constructor.

有关该特定构造函数的更多信息,请参阅此链接。

http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29

http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29

When a constructor calls for a java.lang.Object class, more than likely it's really telling you that you're expected to create your own class (since all Classes ultimately extend java.lang.Object) and that it will interface with that class in a specific way, albeit normally it will call for an interface instead (hence the name) OR it can accept any class and interface with it "abstractly" such as calling .toString() on it. Bottom line, you typically can't just pass it anyclass and expect it to work.

当构造函数调用 java.lang.Object 类时,它很可能真的告诉您希望创建自己的类(因为所有类最终都扩展 java.lang.Object)并且它将与该类交互以一种特定的方式,尽管通常它会调用一个接口(因此得名),或者它可以“抽象地”接受任何类和接口,例如在其上调用 .toString() 。最重要的是,您通常不能将任何类传递给它并期望它起作用。

At any rate, this particular constructor is explained as such:

无论如何,这个特殊的构造函数是这样解​​释的:

Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".

使用 bean getter 从对象构造一个 JSONObject。它反映了对象的所有公共方法。对于每个没有参数且名称以“get”或“is”开头后跟大写字母的方法,调用该方法,并将 getter 方法返回的键和值放入新的 JSONObject。键是通过删除“get”或“is”前缀形成的。如果剩余的第二个字符不是大写,则将第一个字符转换为小写。例如,如果一个对象有一个名为“getName”的方法,并且如果调用 object.getName() 的结果是“Larry Fine”,那么 JSONObject 将包含“name”:“Larry Fine”。

So, what this means is that it's expecting you to create your own class that implements get or is methods (i.e.

所以,这意味着它希望您创建自己的类来实现 get 或 is 方法(即

public String getName() {...}

or

或者

public boolean isValid() {...}

So, to solve your problem, if you really want that higher level of control and want to do some manipulation (e.g. modify some values, etc.) but still use StringBuilder to dynamically generate the code, you can create a class that extends the StringBuilder class so that you can use the append feature, but implement get/is methods to allow JSONObject to pull the data out of it, however this is likely not what you want/need and depending on the JSON, you might spend a lot of time and energy creating the private fields and get/is methods (or use an IDE to do it for you) or it might be all for naught if you don't necessarily know the breakdown of the JSON string.

所以,为了解决你的问题,如果你真的想要更高级别的控制并且想要做一些操作(例如修改一些值等)但仍然使用 StringBuilder 来动态生成代码,你可以创建一个扩展 StringBuilder 的类类,以便您可以使用附加功能,但实现 get/is 方法以允许 JSONObject 从中提取数据,但这可能不是您想要/需要的,并且取决于 JSON,您可能会花费很多时间和精力创建私有字段和 get/is 方法(或使用 IDE 为您做这件事),或者如果您不一定知道 JSON 字符串的细分,这可能是徒劳的。

So, you can very simply call toString()on the StringBuilder which will provide a String representation of the StringBuilder instance and passing that to the JSONObject constructor, such as below:

因此,您可以非常简单地调用toString()StringBuilder,它将提供 StringBuilder 实例的字符串表示并将其传递给 JSONObject 构造函数,如下所示:

...
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
    jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString.toString());
...

回答by Rahul Chauhan

Converting the String to JsonNode using ObjectMapper object :

使用 ObjectMapper 对象将字符串转换为 JsonNode:

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);