java - 用Gson解析Json,没有[]的数组?

标签 java json gson

我需要解析这个 json 文件,但它的格式很奇怪。 https://rsbuddy.com/exchange/summary.json 我正在使用Gson,之前从未处理过Json,所以我很迷茫。

"2": {"buy_average": 191, "id": 2, "sell_average": 191, "name": "Cannonball", "overall_average": 191}

读完这个答案后Parsing JSON from URL

我在这里想出了代码:

    public class AlchemyCalculator {
public static void main(String[] args) throws Exception {

    String json = readUrl("https://rsbuddy.com/exchange/summary.json");

    Gson gson = new Gson();        
    Page page = gson.fromJson(json, Page.class);
    System.out.println(page.items.size());
    for (Item item : page.items)
        System.out.println("    " + item.buy_average);
}


private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            buffer.append(chars, 0, read); 

        System.out.println("{items: [" +buffer.substring(1, buffer.length() -1) + "]}");

        return "{items: [" +buffer.substring(1, buffer.length() -1) + "]}";
    } finally {
        if (reader != null)
            reader.close();

    }
}


static class Item {
    int buy_average;
    int id;
    int sell_average;
    String name;
    int overall_average;

}

static class Page {
    List<Item> items;
}
}

我不明白如何解析它,我看到了一些答案,说要设置一个匹配的对象层次结构,但我不知道如何在这里做到这一点。

预先感谢,并为这里数以百万计的 Json 问题而我无法理解这些问题提前道歉。

最佳答案

如果你确实想使用Gson将字符串解析为Item的列表类中,有一个解决方法如下:

    List<Item> itemsOnPage = new ArrayList<Item>(); 
    String content = readUrl("https://rsbuddy.com/exchange/summary.json");  
    Gson gson = new GsonBuilder().create();
    // the json value in content is like key-value pair which can be treated as a map 
    // {2: item1, 3: item2, 4: item4, .....}
    HashMap<String, Object> items = new HashMap<>();
    items = (HashMap<String, Object>) gson.fromJson(content, items.getClass());
    for (String key : items.keySet()) {
        // Once you have converted the json into a map and since the value associated 
        // with it is also a set of key-value pairs it is treated as LinkedTreeMap
        LinkedTreeMap<String, Object> itemMap = (LinkedTreeMap<String, Object>) items.get(key);
        // convert it back to json representation to that we could 
        // parse it to an object of the Item class
        String itemString = gson.toJson(itemMap);
        // what we have now in itemString is like this:
        // {"id": 2, "name": "Cannonball", "buy_average": 191, "overall_average": 193, "sell_average": 192}
        Item item = new Item();
        item = gson.fromJson(itemString, item.getClass());
        // add the current item to the list
        itemsOnPage.add(item);
    }

你还需要了解的是Json语法。上述 URL 的 json 结构如下:

{
   "2": { ...some details related to item... },
   "3": { ...some details related to item... },
   ...
   ...
}

不能直接解析为List<?>因为事实并非如此。在 Json 中,列表表示为 Array [item1, item2] (检查 http://www.w3schools.com/json/ )而上面的表示是一个字典 - 与每个项目关联的 id,即

{2: item1, 3: item2, 4: item4, .....} 

其中每个项目本身都有一些属性,例如

{"id": 2, "name": "Cannonball", "buy_average": 191, "overall_average": 193, "sell_average": 192}

关于java - 用Gson解析Json,没有[]的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31667449/

相关文章:

java - 在运行时运行 Gluon-Mobile 应用程序时请求 Wifi 权限

java - 从 Node.js 调用 Java Lambda 函数

ios - 如何在 iOS 中发送和接收 Web 服务请求和响应?

java - 如何在jsonobject中设置数组

java - 使用 java 泛型和接口(interface)扩展可比对象

java - cronjob 运行java程序

java - Gson 安全问题

java - 如何使用 Gson 将 JSON 转换为 HashMap?

java - 如何将复杂的ViewGroup复制到位图?

json - Clojure 名称绑定(bind)到 REST JSON 数据