对象数组循环

时间:2018-04-12 13:47:28

标签: java android loops

android java循环问题 json url = https://jsonplaceholder.typicode.com/users 获取示例json url字符串... JSON = String json code;

? itx ['name']不起作用?

                    Gson gson = new Gson();
                Object[] arr = gson.fromJson(JSON, Object[].class);
                int length = arr.length;
                int i=0;
                System.out.println("itxcc = " + length);
                   for(Object itx : arr) {
                       // Like want.. only itx['name'] field
                       System.out.println("itxcc = " + itx.toString());

                   }

日志输出.. ı像accecs打印孩子只有“名字”键或任何东西

04-12 13:37:04.398 4030-4069/com.unovasyon.unovasyon I/System.out: itxcc = {id=1.0, name=Leanne Graham, username=Bret, email=Sincere@april.biz, address={street=Kulas Light, suite=Apt. 556, city=Gwenborough, zipcode=92998-3874, geo={lat=-37.3159, lng=81.1496}}, phone=1-770-736-8031 x56442, website=hildegard.org, company={name=Romaguera-Crona, catchPhrase=Multi-layered client-server neural-net, bs=harness real-time e-markets}}
04-12 13:37:04.398 4030-4069/com.unovasyon.unovasyon I/System.out: itxcc = {id=2.0, name=Ervin Howell, username=Antonette, email=Shanna@melissa.tv, address={street=Victor Plains, suite=Suite 879, city=Wisokyburgh, zipcode=90566-7771, geo={lat=-43.9509, lng=-34.4618}}, phone=010-692-6593 x09125, website=anastasia.net, company={name=Deckow-Crist, catchPhrase=Proactive didactic contingency, bs=synergize scalable supply-chains}}
04-12 13:37:04.399 4030-4069/com.unovasyon.unovasyon I/System.out: itxcc = {id=3.0, name=Clementine Bauch, username=Samantha, email=Nathan@yesenia.net, address={street=Douglas Extension, suite=Suite 847, city=McKenziehaven, zipcode=59590-4157, geo={lat=-68.6102, lng=-47.0653}}, phone=1-463-123-4447, website=ramiro.info, company={name=Romaguera-Jacobson, catchPhrase=Face to face bifurcated interface, bs=e-enable strategic applications}}

ı是新学习的简单例子... 喜欢想..只有itx ['name']字段或任何事情

1 个答案:

答案 0 :(得分:0)

试试这个:要从JSONObject获取密钥的值,您需要在JSONObject

上调用相应的方法
try {
    JSONArray jsonArray = new JSONArray(JSON);
    int length = jsonArray.length();
    int i = 0;
    System.out.println("itxcc = " + length);
    for (int i=0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            System.out.println("itxcc = " + obj.getString("name"));
        }
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }

修改 因此,我假设您的JSON变量包含有效的json string,而且您不需要GSON,如果您想将json映射到您的date: extra operand '+%s' ,则需要这样做类对象。