代码之家  ›  专栏  ›  技术社区  ›  Mark Denom

如何从网页上的JSON数据创建对象?

  •  -1
  • Mark Denom  · 技术社区  · 6 年前

    因此,我试图根据网页上的一些JSON数据创建一个对象列表。

    我的思维过程有点像这样。 以字符串形式下载网站源。 将该字符串传递给GSON,GSON随后从JSON字符串创建对象。 假设我有一个具有正确字段的对象。

    所以像这样

    String data = getURLSource(link);
    JSONObject jsonObj = new JSONObject(data);
    Gson g = new Gson();
    Item p = g.fromJson(jsonObj.toString(), Item.class);
    
    
    public static String getURLSource(String url) throws IOException
        {
            URL urlObject = new URL(url);
            URLConnection urlConnection = urlObject.openConnection();
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    
            return toString(urlConnection.getInputStream());
        }
    
        private static String toString(InputStream inputStream) throws IOException
        {
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
            {
                String inputLine;
                StringBuilder stringBuilder = new StringBuilder();
                while ((inputLine = bufferedReader.readLine()) != null)
                {
                    stringBuilder.append(inputLine);
                }
    
                return stringBuilder.toString();
            }
        }
    

    这会造成错误,所以我的问题是。 从Web源获取JSON数据,然后基于该数据创建对象列表的正确方法是什么?

    这是数据的来源 https://osrsitemapi.azurewebsites.net/api/items

    2 回复  |  直到 6 年前
        1
  •  2
  •   Michał Ziober    6 年前

    我强烈建议使用 Jackson 图书馆有一个伟大的 API 与之合作 JSON 有效载荷。

    假设您的课程如下:

    class Item {
        private int id;
        private String name;
        private boolean members;
        private int sp;
        private int buy_average;
        private int buy_quantity;
        private int sell_average;
        private int sell_quantity;
        private int overall_average;
        private int overall_quantity;
        private String image;
    
        // getters, setters, toString
    
    }
    

    示例用法:

    import com.fasterxml.jackson.databind.ObjectMapper;
    
    import java.net.URL;
    import java.util.stream.Stream;
    
    public class GsonApp {
    
        public static void main(String[] args) throws Exception {
            URL urlObject = new URL("https://osrsitemapi.azurewebsites.net/api/items");
    
            ObjectMapper mapper = new ObjectMapper();
            Item[] items = mapper.readValue(urlObject, Item[].class);
    
            System.out.println("Number of items: " + items.length);
            System.out.println("Show 10 items:");
            Stream.of(items).limit(10).forEach(System.out::println);
        }
    }
    

    以上代码打印:

    Number of items: 3344
    Show 10 items:
    Item{id=2, name='Cannonball', members=true, sp=5, buy_average=202, buy_quantity=641812, sell_average=202, sell_quantity=1075463, overall_average=202, overall_quantity=1717275, image='https://oldschool.runescape.wiki/images/thumb/7/73/Cannonball_detail.png/150px-Cannonball_detail.png?8724b'}
    Item{id=36, name='Candle', members=true, sp=3, buy_average=182, buy_quantity=39, sell_average=136, sell_quantity=5, overall_average=177, overall_quantity=44, image='https://oldschool.runescape.wiki/images/thumb/8/83/Candle_detail.png/50px-Candle_detail.png?9db36'}
    Item{id=30, name='Bucket of wax', members=true, sp=6, buy_average=820, buy_quantity=10, sell_average=0, sell_quantity=0, overall_average=820, overall_quantity=10, image='https://oldschool.runescape.wiki/images/thumb/0/0a/Bucket_of_wax_detail.png/130px-Bucket_of_wax_detail.png?838bd'}
    Item{id=8, name='Cannon stand', members=true, sp=187500, buy_average=191566, buy_quantity=10, sell_average=187186, sell_quantity=22, overall_average=188555, overall_quantity=32, image='https://oldschool.runescape.wiki/images/thumb/7/76/Cannon_stand_detail.png/150px-Cannon_stand_detail.png?c4958'}
    Item{id=43, name='Adamant arrowtips', members=true, sp=40, buy_average=94, buy_quantity=2321, sell_average=99, sell_quantity=19945, overall_average=99, overall_quantity=22266, image='https://oldschool.runescape.wiki/images/thumb/7/7e/Adamant_arrowtips_detail.png/120px-Adamant_arrowtips_detail.png?bdf02'}
    Item{id=12, name='Cannon furnace', members=true, sp=187500, buy_average=192005, buy_quantity=11, sell_average=188086, sell_quantity=19, overall_average=189523, overall_quantity=30, image='https://oldschool.runescape.wiki/images/thumb/d/d0/Cannon_furnace_detail.png/130px-Cannon_furnace_detail.png?c4958'}
    Item{id=40, name='Iron arrowtips', members=true, sp=2, buy_average=5, buy_quantity=6260, sell_average=4, sell_quantity=5817, overall_average=5, overall_quantity=12077, image='https://oldschool.runescape.wiki/images/thumb/5/5d/Iron_arrowtips_detail.png/120px-Iron_arrowtips_detail.png?7d8a1'}
    Item{id=42, name='Mithril arrowtips', members=true, sp=16, buy_average=49, buy_quantity=16934, sell_average=0, sell_quantity=0, overall_average=49, overall_quantity=16934, image='https://oldschool.runescape.wiki/images/thumb/2/21/Mithril_arrowtips_detail.png/120px-Mithril_arrowtips_detail.png?3b5f0'}
    Item{id=39, name='Bronze arrowtips', members=true, sp=1, buy_average=8, buy_quantity=100, sell_average=4, sell_quantity=8065, overall_average=4, overall_quantity=8165, image='https://oldschool.runescape.wiki/images/thumb/8/84/Bronze_arrowtips_detail.png/120px-Bronze_arrowtips_detail.png?0c3c4'}
    Item{id=10, name='Cannon barrels', members=true, sp=187500, buy_average=188888, buy_quantity=9, sell_average=187594, sell_quantity=19, overall_average=188010, overall_quantity=28, image='https://oldschool.runescape.wiki/images/thumb/5/54/Cannon_barrels_detail.png/125px-Cannon_barrels_detail.png?7aa5b'}
    
    1. Jackson
    2. Jackson JSON Tutorials
        2
  •  1
  •   M. Oberauer    6 年前

    首先,我建议从源代码中去掉JSON数据周围的XML包装,如果您查看源代码,您会发现它不是以有效的JSON开始的,而是:

    <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">

    而且数据包含多个项目,因此您应该要求GSON提供 List<Item> 而不仅仅是 Item .

    如果您的item类提供了正确的字段,那么应该可以工作。