2015-04-20 29 views
1

我转换JSONObject的字符串与杰克逊解析它在JsonNode,但我有一个列表,我的JSONObject,当我用ObjectMapper分析它,我得到这个:的JSONObject与清单字符串JsonNode

["{Property1 : value1, Property2 : value2}"] 

而且我不能拨打myJsonNodeObject.get(i).get("Property1")这是我的问题。

我试图在我的JSONObject的JSONArray中投我的列表,但不工作。

resultAsJSONObject = new JSONObject(); 
resultAsJSONObject.put("Label", getMetricStatisticsResult.getLabel()); 
resultAsJSONObject.put("Datapoints", getMetricStatisticsResult.getDatapoints()); 
resultAsJSONObject.put("fromDate", fromDate.getTimeInMillis()); 
resultAsJSONObject.put("toDate", toDate.getTimeInMillis()); 
resultAsJSONObject.put("error", ""); 
resultAsString = resultAsJSONObject.toString(); 

mapper.readValue(resultAsString, MetricsData.class); 
+1

能否请您分享您的'MetricsData'豆你如何使用它? – mtyurt

+0

为什么?你不需要它。问题是JSONObject中的列表(getMetricsStatisticsResult.getDatapoints()返回列表),它将转换为具有此格式[“{Property1:value1,Property2:value2}”]的字符串,但它是错误的,我需要这种格式:[{ Property1“:”value1“,”Property2“:”value2“}”]。 – Florian

+0

我想知道,为什么使用JSONObject?你可以直接删除它吗? –

回答

2

假设您有一个您只想更改的JSON字符串。然后,您可以使用Jackson将其解析为ObjecNode,然后对其进行修改。这里有一个例子:

public class JacksonModifyJson { 

    static final String JSON = "{\"name\":\"Bob\", \"age\":13}"; 

    public static void main(String[] args) throws IOException { 
     final ObjectMapper mapper = new ObjectMapper(); 
     final ObjectNode jsonNode = mapper.readValue(JSON, ObjectNode.class); 
     jsonNode.put("url", "example.com"); 
     System.out.println(mapper.writeValueAsString(jsonNode)); 
    } 
} 

输出:

{"name":"Bob","age":13,"url":"example.com"}