具有非固定键的对象的获取属性 [英] Getting property of an object which has non-fixed keys

查看:45
本文介绍了具有非固定键的对象的获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我从网络服务获得此JSon响应:

Assume that I get this JSon Response from webservice:

{
    "id":13,
    "name":"Alireza",
    "required_id":"14",
    "all_friends_id_and_name":{
        "28":"Hassan",
        "21":"Mohammad",
        "68":"Ali",
        "14":"Taha",
        "96":"Darya"
    }
}

在此响应中,required_id值指定我需要一个ID为14的朋友名称,因此在all_friends_id_and_name对象中,我应获取值"14"(塔哈),并在我的应用中使用它.

In this response required_id value specifies that I need a friend name with id 14, so in all_friends_id_and_name object I should get the value of "14" (Taha) and use it in my app.

我正在使用Retrofit2和gson库.

I'm using retrofit2 and gson libraries.

如何获取具有非固定键的对象的属性?

How to get property of an object which has non-fixed keys?

推荐答案

对于本机方法,可以尝试使用

For Native approach, You can Try with Iterator .

迭代器是使程序员能够遍历一个对象的对象. 容器,尤其是列表.

An iterator is an object that enables a programmer to traverse a container, particularly lists.

 "all_friends_id_and_name":{
        "28":"Hassan",
        "21":"Mohammad",
        "68":"Ali",
        "14":"Taha",
        "96":"Darya"
    }

对于以上部分,您的 LOGIC 将是

For the above section, Your LOGIC will be

     JSONObject jsonData = new JSONObject("Json_response");
          Iterator  iteratorObj = jsonData .keys();
           while (iteratorObj.hasNext())
            {
                String str_json_Key = (String)iteratorObj.next();
                 // Print=28,21....96
             }

这篇关于具有非固定键的对象的获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆