【问题标题】:Parsing JSON file with different number of keys使用不同数量的键解析 JSON 文件
【发布时间】:2014-05-12 14:49:00
【问题描述】:

我的 JSON 文件包含具有相同键的字符串,但其中一些字符串不会出现在某些字符串中。例如:

{
    "city": "CB1 2BH Cambridge",
    "addr": "Devonshire Road 1",
    "title": "Devonshire Arms",
    "phone": "+44 1223 6610"
},
{
    "city": "E8 1JH London",
    "addr": "Amhurst Road 90",
    "title": "Pembury Tavern",
    "web": "http://www.individualpubs.co.uk/pembury/"
},
{
    "web": "http://bandholmhotel.dk/",
    "title": "Bandholm Hotel",
},
{
    "city": "00100 Helsinki",
    "addr": "Pohjoinen Rautatiekatu 23",
    "title": "Helkan Baari",
    "country": "FI"
},

如何在android中正确解析?

【问题讨论】:

    标签: android json parsing arrays jsonobject


    【解决方案1】:

    考虑到这是你的 JSONArray,

    尝试如下操作,

        for (int i = 0; i < jsonArray.length(); i++) {
             JSONObject jObj = (JSONObject) jsonProductArray.getJSONObject(i);
        String city = jObj.optString("city", "cityDefaultValue");
        String addr = jObj.optString("addr", "addDefaultValue");
        String title = jObj.optString("title", "titleDefaultValue");
        String phone = jObj.optString("phone", "phoneDefaultValue");
    }
    

    【讨论】:

    • 在这种情况下如何处理例如没有“电话”字段的对象?
    • @smartmouse 我已根据您的要求编辑了答案,希望对您有所帮助。
    【解决方案2】:

    一种可能的解决方案是拥有一个模态类并使用 Gson 库来解析 Json。

    您可以在模态类中设置一些默认值,用于在 Json 中找不到值的键

    【讨论】:

      【解决方案3】:

      用json的key创建模型类,使用gson解析成模型类。

      A a = gson.fromJson(jsonRes.toString(),A.class);
      here A is your model class and a is the instance of A
      

      【讨论】:

        【解决方案4】:

        您可以使用 Gson 库。 创建类似的东西

        class SomeObjects {
        @SerializedName("city")
        private String mCity;
        @SerializedName("addr")
        private String mAddres;
        ...
        }
        

        然后

        SomeObject obj = new Gson.fromJson(jsonString, SomeObject.class); 
        

        你也可以直接序列化到数组中

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-30
          • 2021-06-25
          • 1970-01-01
          • 1970-01-01
          • 2022-01-25
          相关资源
          最近更新 更多