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

时间:2019-02-10 22:25:45

标签: java json gson

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

我的思考过程有点像这样。 以字符串形式下载网站的源代码。 将该字符串传递到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();
        }
    }

那会引发错误,所以我的问题是。 从网络源获取json数据,然后基于该数据创建对象列表的正确方法是什么。

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

2 个答案:

答案 0 :(得分:2)

我强烈建议使用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

答案 1 :(得分:1)

首先,我建议摆脱源中有关JSON数据的XML包装,如果您查看源,您会发现它不是以有效的JSON开头,而是这样:

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

数据还包含多个项目,因此您应该要求Gson提供List<Item>,而不只是Item

如果您的Item-class提供正确的字段,则应该可以使用。