0

I need to parse a below JSON:

{
"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
    }
]
}

That is: The Json contains: 2 elements ("this_year_ti" and "last_year_ti") and 2 arrays ("this_year" and "last_year").
How can I parse it into an Object A that have 2 strings and 2 lists?
Please help me with this difficulty.

Yugesh
  • 4,030
  • 9
  • 57
  • 97
Ngo Van
  • 857
  • 1
  • 21
  • 37

2 Answers2

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"));

}

CoderDecoder
  • 445
  • 4
  • 18
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);
    }

}
prakash
  • 560
  • 4
  • 14