Android ArrayAdapter and JSONArray

后端 未结 4 2018
忘了有多久
忘了有多久 2021-01-07 10:48

I am new to Android Development.

I purely like to work with JSON Objects and Arrays for my simple application considering the lightness of the JSON Carrier compared

4条回答
  •  忘掉有多难
    2021-01-07 11:13

    I would advise you to use google GSON instead JSON. It is a library that gives you a create objects from JSON-request, and you don't need to parse JSON everymore. Just create an object which contains all the fields from your JSON request and are named the same, and do with it whatever you want - for example:

    Your JSON request
    {
        [
            {
                "id": "2663",
                "title":"qwe"
    
            },
            {
                "id": "1234",
                "title":"asd"
            },
            {
                "id": "5678",
                "title":"zxc"
            }
    
        ]
    }
    

    Your class - item of JSON-Array

     public class MyArrayAdapterItem{
         int id;
         String title;
     }
    

    Somwhere in your code where you downloading data. I didn't know how are you doing it so i'll post my code for example:

    mGparser = new JsonParser();
    Gson mGson = new Gson();
    
    Url url = "http://your_api.com"
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Connection", "close");
    conn.connect();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
    JsonArray request = (JsonArray) mGparser.parse(in.readLine());
    in.close();
    ArrayList items = mGson.fromJson(request, new TypeToken>() {}.getType());
    

    So that's all, for now just put "items" instead JSON-array in your adapter's constructor

提交回复
热议问题