【问题标题】:JsonArray and GsonJsonArray 和 Gson
【发布时间】:2014-02-04 12:54:30
【问题描述】:

我使用的 JSON 库是 Gson。我很难制定一个有效的数据类型来表示以下 JSON 字符串:

{  
   "latestoffers": [
      {
         "id": "4qXleunwNMCKi8M0q0CuMa",
         "price": "534.99",
         "firstrecorded_at": 1377808800,
         "lastrecorded_at": 1382862800,
         "seller": "Newegg",
         "availability": "In stock. [BBX: Buy Box]",
         "currency": "USD"
      },
      {
         "id": "4xTIQAPySG68IS0CGyOuyO",
         "price": "582.41",
         "firstrecorded_at": 1380725000,
         "lastrecorded_at": 1382862800,
         "seller": "Beach Audio",
         "currency": "USD"
      },
      {
         "id": "5nW67R2V4CwmE8cwaWsawe",
         "price": "578.04",
         "firstrecorded_at": 1379524200,
         "lastrecorded_at": 1379998900,
         "seller": "Beach Audio",
         "currency": "USD"
      }
      ],
   "offers_count": 6,
   "name": "newegg.com",
   "recentoffers_count": 2,
   "sku": "N82E16834216463",
   "url": "http://www.newegg.com/Product/Product.aspx?Item=N82E16834216463"
}

我的数据类(到目前为止)如下,我不知道如何完成的方法getOfferData()。我也不确定 JsonArray 是否是要使用的合适的 JSON 元素?

static class LatestOffers {

    Integer offers_count;
    String name;
    Integer recentoffers_count;
    String sku;
    String url;

    java.util.List<JsonArray> getOfferData() {

        List<JsonArray> list = new ArrayList<JsonArray>();
        // how do I get parse the 'id', 'price', 'firstrecorded_at' etc. to add them to the ArrayList?
          return list;
    }

    Integer getOffers_count() {
        return offers_count;
    }

    String getName() {
        return name;
    }

    Integer getRecentoffers_count() {
        return recentoffers_count;
    }

    String getSku() {
        return sku;
    }

    String getUrl() {
        return url;
    }
}

有什么帮助吗?谢谢。

编辑

事实证明我不必要地使事情复杂化,这按预期工作:

static class LatestOffers {
        List<Offer> latestoffers;

        List<Offer> getOffer() {
            return latestoffers;
        }
    }

    static class Offer {

        private String id;
        private String price;
        private long firstrecorded_at;
        private long lastrecorded_at;
        private String seller;
        private String availability;
        private String currency;

        String getId() {
            return id;
        }

        String getPrice() {
            return price;
        }

        long getFirstrecorded_at() {
            return firstrecorded_at;
        }

        long getLastrecorded_at() {
            return lastrecorded_at;
        }

        String getSeller() {
            return seller;
        }

        String getAvailability() {
            return availability;
        }

        String getCurrency() {
            return currency;
        }

    }

感谢所有回答的人,我接受 user2762451 的回答,因为他是第一个建议使用另一个类作为 Offer 数据的人。

【问题讨论】:

    标签: json gson arrays


    【解决方案1】:

    我建议你为数组中的对象创建新的 POJO。

    class Offer {
        private String id;
        private String price;
        private long firstRecordedAt;
        private long lastRecordedAt;
        private String seller;
        private String availability;
        private String currency;
    

    }

    您的LatestOffers 类可以有一个List&lt;Offer&gt; offers;,而getOfferData() 方法应该返回List&lt;Offer&gt;

    基本上如下:

    static class LatestOfferDetail {
        private int offersCount;
        private String name;
        private int recentOffersCount;
        private String sku;
        private String url;
        private List<Offer> latestOffers = new ArrayList<Offer>();
    
        //other getters and setters
        public List<Offer> getLatestOffers() {
            return latestOffers;
        }
    }
    

    此外,您似乎在同一段代码和 JSON 中遵循多个命名约定。对于 JAVA,建议遵循 CamelCaseNaming。我已经更新了答案以反映这些。

    另外,latestOffers 的 getter 方法的名称与约定不同。建议将其命名为 get{FieldName}。我已经更新了答案以反映这一点。

    【讨论】:

    • 感谢您,user2762451。我知道到目前为止,我的问题是如何解析 JSON 以获取 id、价格、firstRecordedAt 等 - 关键是(与 sku、url 等不同)没有我可以使用的键值检索优惠?
    • @ClivevanHilten latestOffers 是一个列表,实际上是一个数组,并且 JSON 中的数组元素不会有这样的“键”。当你说“我可以用来检索 Offer 的键值”时,你到底想做什么?
    • 我不知道如何检索包含 id、price、firstRecordedAt 等的数组以便将它们添加到列表中?
    • @ClivevanHilten 很高兴它有效并且很高兴能提供帮助!顺便说一句,我是“他”:)
    【解决方案2】:

    创建另一个 POJO,包含数组中使用的所有参数,如下所示:

    public class MyOffer  
    {  
      private String id;  
      private double price;  
      private long firstrecorded_at;  
      private long lastrecorded_at;  
      private String seller;  
      private String availability;  
      private String currency;  
    
      //your getter and setter methods here.
    }   
    

    在您的班级中包含上述 pojo 的列表LatestOffers

    List<MyOffer> latestoffers = new ArrayList<MyOffer>();    
    

    你的班级LatestOffers 看起来像这样

    static class LatestOffers   
    {
        Integer offers_count;
        String name;
        Integer recentoffers_count;
        String sku;
        String url;
    
        List<MyOffer> latestoffers = new ArrayList<MyOffer>();
    
        //getter and setter method
    }
    

    测试主类:

    public static void main(String[] args) {
        LatestOffers lso = new LatestOffers();
        lso.setName("N82E16834216463");
        lso.setOffers_count(6);
        lso.setRecentoffers_count(2);
        lso.setSku("N82E16834216463");
        lso.setUrl("http://www.newegg.com/Product/Product.aspx?Item=N82E16834216463");
        MyOffer offer = null;
        List<MyOffer> list = new ArrayList<MyOffer>();
        for(int i=0;i<2;i++){
            offer = new MyOffer();
            offer.setAvailability("In stock. [BBX: Buy Box]");
            offer.setCurrency("USD");
            offer.setFirstrecorded_at(1377808800);
            offer.setId("4qXleunwNMCKi8M0q0CuMa");
            offer.setLastrecorded_at(1382862800);
            offer.setPrice(534.99);
            offer.setSeller("Newegg");
    
            list.add(offer);
        }
        lso.setLatestoffers(list);
        Gson gson = new Gson();
        String json = gson.toJson(lso);
        System.out.println(json);
    
    }
    

    输出:

    {
      "offers_count": 6,
      "name": "N82E16834216463",
      "recentoffers_count": 2,
      "sku": "N82E16834216463",
      "url": "http://www.newegg.com/Product/Product.aspx?Item=N82E16834216463",
      "latestoffers": [
        {
            "id": "4qXleunwNMCKi8M0q0CuMa",
            "price": 534.99,
            "firstrecorded_at": 1377808800,
            "lastrecorded_at": 1382862800,
            "seller": "Newegg",
            "availability": "In stock. [BBX: Buy Box]",
            "currency": "USD"
        },
        {
            "id": "4qXleunwNMCKi8M0q0CuMa",
            "price": 534.99,
            "firstrecorded_at": 1377808800,
            "lastrecorded_at": 1382862800,
            "seller": "Newegg",
            "availability": "In stock. [BBX: Buy Box]",
            "currency": "USD"
        }
      ]
    }
    

    无需定义getOfferData() 方法只需创建MyOffer 类的列表并将该列表设置为latestoffers 列表定义在您的类LatestOffers 中。当您将 POJO 转换为 JSON 字符串时,它会将您的列表序列化为 JsonArray。

    【讨论】:

    • 谢谢你的这个 Yagnesh。您能否更新您的答案以包含涵盖您的观点的代码“当您将 POJO 转换为 JSON 字符串时,它会将您的列表序列化为 JsonArray”?这就是我难以理解的一点。
    • 它会将您的列表转换为 JSON 字符串中的数组。
    • 对不起,我不明白对我的评论的回复。如果你有时间,代码(甚至是伪代码)会很有帮助,所以我可以理解 :-)
    • 请看我更新的答案。我创建了将您的数据添加到列表以及LatestOffers 类对象的测试方法,最后我使用 GSON api 将我的对象转换为 JSON。输出与您想要的相同。如果您仍然需要任何帮助,那就来吧。
    • 非常感谢您对这个问题的帮助。正如我对问题的编辑所示,我接受了 user2762451 的回答,因为他是第一个建议对 Offer 数据使用另一个类的人。
    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多