我正在尝试从字符串创建一个json对象。我从服务器获取此字符串,然后替换“与\”。但我仍然得到错误。 这是我的json
{
"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);
我传递的repsonseStr值是
{\"tasks\":[{\"id\":\"activiti$1942\",\"description\":\"reviewthedoc\",\"dueDate\":\"9999-06-1216:01:47GMT+0530(IST)\",\"status\":\"NotYetStarted\",\"priority\":\"2\",\"startDate\":\"2015-06-1112:26:30GMT+0530(IST)\",\"type\":\"Review\",\"completeness\":\"0\",\"resources\":[{\"nodeRef\":\"workspace://SpacesStore/5d313010-5359-4749-8d8e-935bd073999c\",\"fileName\":\"plcfanuclinks\",\"displayName\":\"plcfanuclinks\",\"location\":{\"site\":\"hix-project\",\"container\":\"documentLibrary\",\"path\":\"\"},\"icon\":\"/images/filetypes/_default.gif\"}],\"transitions\":[{\"id\":\"Next\",\"label\":\"TaskDone\"}]}]}
任何人都可以提供帮助。错误是
org.json.JSONException:缺少值1 [字符2第1行]
答案 0 :(得分:0)
删除替换,服务器输出是有效的JSON。
使用Jackson(请参阅https://github.com/FasterXML/jackson)作为JSON解析器,以下代码可以正常工作(这里我使用的文件输入流从文件test.json
读取问题中给出的输入,但是替换为输入流response.getEntity().getContent()
将以相同的方式工作):
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>