Java 从字符串创建Json对象时出现Json异常
我试图从一个字符串创建一个json对象。我从服务器获取此字符串,然后将“替换为\”。但我还是犯了个错误。 这是我的jsonJava 从字符串创建Json对象时出现Json异常,java,json,jsonexception,Java,Json,Jsonexception,我试图从一个字符串创建一个json对象。我从服务器获取此字符串,然后将“替换为\”。但我还是犯了个错误。 这是我的json { "tasks": [ { "id": "activiti$1942", "description": "review the doc", "dueDate": "9999-06-11 12:26:48 GMT+0530 (IST)", "status": "Not Yet Started",
{
"tasks":
[
{
"id": "activiti$1942",
"description": "review the doc",
"dueDate": "9999-06-11 12:26:48 GMT+0530 (IST)",
"status": "Not Yet Started",
"priority": "2",
"startDate": "2015-06-11 12:26:30 GMT+0530 (IST)",
"type": "Review",
"completeness": "0",
"resources":
[
{
"nodeRef": "workspace://SpacesStore/5d313010-5359-4749-8d8e-935bd073999c",
"fileName": "plc fanuc links",
"displayName": "plc fanuc links",
"location":
{
"site": "hix-project",
"container": "documentLibrary",
"path": ""
},
"icon": "/images/filetypes/_default.gif"
}
],
"transitions":
[
{
"id": "Next",
"label": "Task Done"
}
]
}
]
}
这是我的java代码
BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder responseString = new StringBuilder();
String line = "";
while ((line = breader.readLine()) != null) {
responseString.append(line);
}
breader.close();
String repsonseStr = responseString.toString();
repsonseStr = repsonseStr.replaceAll("\\s+","");
repsonseStr = repsonseStr.replace("\"", "\\\"");
System.out.println("repsonseStr =" + repsonseStr);
JSONObject object= new JSONObject(repsonseStr);
//JSONArray tsmresponse = (JSONArray) myResponse.get("tasks");
ArrayList<String> list = new ArrayList<String>();
org.json.JSONArray array = object.getJSONArray("tasks");
for(int i=0; i<array.length(); i++){
try {
list.add(array.getJSONObject(i).getString("id"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(list);
有人能帮忙吗。错误是
org.json.JSONException:1处缺少值[字符2第1行]
如果删除替换项,则服务器输出是有效的JSON 使用Jackson(请参阅)作为JSON解析器,以下代码可以工作(这里我使用一个文件输入流,从文件
test.JSON
中读取问题中给出的输入,但是用输入流response.getEntity().getContent()
替换它将同样工作):
Jackson的maven依赖性:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>
com.fasterxml.jackson.core
杰克逊数据绑定
2.5.4
为什么要用\“
替换”
?原始字符串是有效的JSON-您的munged版本不是。您使用的是哪个JSON库?org.json?在任何替换/转换后,您可以使用检查json。感谢您的回复…我的问题已经解决。我导入了错误的json库。
try {
FileInputStream stream = new FileInputStream("test.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(stream);
JsonNode tasks = node.get("tasks");
for (JsonNode task : tasks) {
System.out.println(task.toString());
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>