迭代JSON字符串并将值存储在Java类中

时间:2018-06-21 22:16:02

标签: java arrays json

我正在尝试遍历json字符串并将值存储在Java中的类上。我已经在C#上完成了此操作,但是不知道如何在Java上执行此操作。这是我的json:

{"status":"ok",
    "totalResults":20,
    "articles":[
            {"source":{
                "id":"srcId",
                "name":"srcName"},
            "author":"Some Author",
            "title":"Some Title",
            "description":"Some description.",
            "url":"SomeUrl",
            "urlToImage":"URL to image",
            "publishedAt":"2018-06-21T20:56:00Z"},
            {"source":{
                "id":"srcId",
                "name":"srcName"},
            "author":"Some Author",
            "title":"Some Title",
            "description":"Some description.",
            "url":"SomeUrl",
            "urlToImage":"URL to image",
            "publishedAt":"2018-06-21T20:56:00Z"}
    ]
}

它来自HttpUrlConnection,当我使用C#编写时,是这样的:

var results = await DataService.GetDataFromService(queryString).ConfigureAwait(false);

List<MyClass> lstItems = new List<MyClass>();
var myClass = new MyClass();

int i = 0;

    foreach (var item in myList)
    {
        if (item != null)
        {
            myClass.sourceId = results["articles"][i]["source"]["id"].ToString();
            myClass.sourceName = results["articles"][i]["source"]["name"].ToString();
            myClass.auth = results["articles"][i]["author"].ToString();
            myClass.title = results["articles"][i]["title"].ToString();

            lstItems.Add(myClass);
            i++;
        }
    }

我已经尝试过JSONObject和JSONParser,但不知道我必须使用那些类中的哪些方法来做同样的事情。我想在没有GSon库或任何其他第三方库的情况下进行此操作,如果有人可以帮助的话,我将非常感激。

谢谢。

0 个答案:

没有答案