2015-04-20 31 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"}