2014-03-12 51 views
0

2個陣列我需要解析下面JSON:解析JSON與Android中

{ 
"this_year_ti": "TYMN01", 
"last_year_ti": "LYMN01", 
"this_year": [ 
    { 
     "date": "20140310 14:20:10", 
     "amount": 5.2, 
     "usage": 3.2, 
     "ratio": 1 
    }, 
    { 
     "date": "20140310 14:20:10", 
     "amount": 5.2, 
     "usage": 3.2, 
     "ratio": 1 
    } 
], 
"last_year": [ 
    { 
     "date": "20130310 15:20:10", 
     "amount": 6.87, 
     "usage": 4.2, 
     "ratio": 2 
    }, 
    { 
     "date": "20130310 15:20:10", 
     "amount": 6.87, 
     "usage": 4.2, 
     "ratio": 2 
    } 
] 
} 

即:將JSON包含:2個元素( 「this_year_ti」 和 「last_year_ti」)和2門陣列( 「THIS_YEAR」和「last_year」)。
我如何解析它到一個有2個字符串和2個列表的對象A?
請幫我解決這個難題。

+0

[GOOGLE-GSON](https://code.google.com/p/google-gson/)可以提供幫助。 –

+0

請閱讀此:http://stackoverflow.com/questions/443499/json-to-map –

+0

你試過的東西,直到。 – Yugesh

回答

0
JSONObject response = jObject.getJSONObject("response"); 
    JSONArray list = response.getJSONArray("this_year"); 
    JSONArray list1 = response.getJSONArray("last_year"); 
    for (int i = 0; i < list.length(); i++) { 

JSONObject j = list.getJSONObject(i); 
JSONObject k = list.getJSONObject(i); 
date1.add(j.getString("date")); 
date2.add(k.getString("date")); 
amount1.add(j.getString("amount")); 
amount2.add(k.getString("amount")); 
usage1.add(j.getString("usage")); 
usage2.add(k.getString("usage")); 
ratio1.add(j.getString("ratio")); 
ratio2.add(k.getString("ratio")); 

}

0
You can use GSON for this. Here's an example 

public class MyInternalClass { 

    public String date; 
    public float amount; 
    public float usage; 
    public int ratio; 

} 

public class MyClass { 

    public String this_year_ti; 
    public String last_year_ti; 
    public List<MyInternalClass> this_year; 
    public List<MyInternalClass> last_year; 

} 

public class MyBusinessClass { 

    public void parseJson() { 
     Gson gson = new Gson(); 
     MyClass myClass = gson.fromJson(json, MyClass.class); 
    } 

}