簡體   English   中英

用Gson解析Json,沒有[]的數組?

[英]Parsing Json with Gson, an array without [ ]?

我需要解析這個json文件,但是它的格式很奇怪。 https://rsbuddy.com/exchange/summary.json我正在使用Gson,而且我之前從未與Json打過交道,所以我很失落。

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

閱讀此答案后, 從URL解析JSON

我在這里提出了代碼:

    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問題向您致歉,我無法從這些問題中理解。

您可以嘗試使用JsonReader來流化json響應並像這樣解析它:

    Reader streamReader = new InputStreamReader(url.openStream());
    JsonReader reader = new JsonReader(streamReader);
    reader.beginObject();
    while (reader.hasNext()) {
         String name = reader.nextName(); //This is the JsonObject Key
         if (isInteger(name)) {
             reader.beginObject();
             while (reader.hasNext()) {
                 String name = reader.nextName();
                 if (name.equals("id")) {
                     //get the id
                 } else if (name.equals("name")) {
                     //get the name
                 } else if (name.equals("buy_average")) {
                     //get the buy average
                 } else if (name.equals("overall_average")) {
                     //get the overall average
                 } else if (name.equals("sell_average")) {
                     //get the sell average
                 } else {
                     reader.skipValue();
                 }
             }
             reader.endObject();
         }
    }
    reader.endObject();
    reader.close();

其中isInteger是一個函數:

public static boolean isInteger(String str) {
    if (str == null) {
        return false;
    }
    int length = str.length();
    if (length == 0) {
        return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
        if (length == 1) {
            return false;
        }
        i = 1;
    }
    for (; i < length; i++) {
        char c = str.charAt(i);
        if (c < '0' || c > '9') {
            return false;
        }
    }
    return true;
}

如果您確實想使用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中,列表表示為數組[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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM