2012-09-10 43 views
0

我一直在使用stock org.json庫,並且熟悉這一點。我現在想出於性能原因使用Jackson庫,但我正在努力適應看起來像一個非常不同的框架。看看下面的JSON:將org.json中的庫更改爲Jackson解析JSON

{"result":[[{"usUserName":"FRED","usActive":true},{"usUserName":"JIM","usActive":true},{"usUserName":"DAVID","usActive":true}]]} 

隨着org.json我解析這個如下:

try { 
    JSONArray jsonRecordset = response.getJSONArray("result").getJSONArray(0); 
    JSONObject jsonFirstRecord = jsonRecordset.getJSONObject(0); 
    Log.i("myloginfo", jsonFirstRecord.getString("usUserName")); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

我想與傑克遜複製這一點,但看不到哪裏去,因爲它看起來非常不同。我的JSON來自我無法控制的Web服務。以上數據僅用於說明,我的實際數據要大得多,因此我希望獲得最佳性能。

回答

1

通常的方法是,您不需要手動切片和切片,而是定義一個Java類(或多個類),它具有與JSON結構兼容的結構。像這樣:

public class Response { 
    public UserInfo[][] result; 
} 
public class UserInfo { 
    public String usUserName; 
    public boolean usActive; 
} 

ObjectMapper mapper = new ObjectMapper(); // must reuse for good performance 
Response resp = mapper.readValue(jsonInput, Response.class); 
// and use 'resp' however you want, now has the expected data. 

它也可能使用傑克遜一樣json.org,所謂樹模型;爲此你可以看看教程。如果數據沒有良好的對象結構(即不能從OO語言輕鬆訪問),或者只需要大型文檔中的一小段代碼,它就會更好。

+0

非常感謝,只是我需要的代碼提示! –