Как получить значение из вложенного JSON - PullRequest
0 голосов
/ 28 мая 2018

У меня есть следующий JSON.

Данные:

{
posts: [{
    thread: {
        uuid: "8d4d59ad10e0b5df2a9f3cac30f1a6b96e809233",
        url: "http://www.esquire.com/entertainment/news/a53604/deadpool-2-teaser/",
        site_full: "www.esquire.com",
        site: "esquire.com",
        site_section: "",
        site_categories: [
            "news",
            "entertainment",
            "education"
        ],
        section_title: "",
        title: "The Deadpool 2 Teaser Just Dropped and It's Great",
        title_full: "The Deadpool 2 Teaser Just Dropped and It's Great",
        published: "2017-03-05T00:45:28.810+02:00",
        replies_count: 0,
        participants_count: 0,
        site_type: "news",
        country: "US",
        spam_score: 0.127,
        main_image: "http://esq.h-cdn.co/assets/17/09/1600x800/landscape-1488661852-            deadpool2-630x400-copy.jpg",
        performance_score: 9,
        domain_rank: 1790,
        social: {
            facebook: {
                likes: 999,
                comments: 0,
                shares: 999
            },
            gplus: {
                shares: 0
            },
            pinterest: {
                shares: 0
            },
            linkedin: {
                shares: 0
            },
            stumbledupon: {
                shares: 0
            },
            vk: {
                shares: 0
            }
        }
    },
    uuid: "XXXXX",
    url: "http://www.esquire.com/entertainment/news/a53604/deadpool-2-teaser/",
    ord_in_thread: 0,
    author: "Peter Wade",
    published: "2017-03-05T00:45:28.810+02:00",
    title: "The Deadpool 2 Teaser Just Dropped and It's Great",
    text: "The Deadpool 2 Teaser Just Dropped and It's Great "
    Anyone know the number to 911 ? " Most Popular By Peter Wade Mar 4, 2017 The Deadpool 2 teaser trailer that has been playing exclusively in theaters before Logan was officially released by Ryan Reynolds on Saturday. As expected, Deadpool is still a second-rate hero and a fan of butt jokes, struggling to even get his super hero suit on Superman-style in a phone booth while a senior citizen is being mugged nearby. Related Story Ryan Reynolds Was Kind to Drugged-Up Deadpool Fan Advertisement - Continue Reading Below "
    Somebody save me!Is there anybody in this world who can help me,
    for God 's sake?" the man screams helplessly while Reynolds'
    Deadpool smashes his ass against the booth 's glass. GIF Most Popular Then Stan Lee appeared, and things went downhill from there. If you look closely, another clue lurks in the form of graffiti on the side of the phone booth that reads, "Nathan Summers, Cumming Soon!" The name is a reference to X-Men character Cable, a.k.a. Nathan Summers, hinting that he may be Deadpool'
    s foe this time around.Deadpool 2 is a little less than a year away,
    with a scheduled release date of March 2,
    2018. Related Story ",
    highlightText : "",
    highlightTitle: "",
    language: "english",
    external_links: [],
    entities: {
        persons: [{
                name: "reynolds",
                sentiment: "none"
            },
            {
                name: "deadpool",
                sentiment: "none"
            },
            {
                name: "peter wade mar",
                sentiment: "none"
            },
            {
                name: "ryan reynolds",
                sentiment: "none"
            },
            {
                name: "stan lee",
                sentiment: "none"
            },
            {
                name: "nathan summers",
                sentiment: "none"
            }
        ],
        organizations: [{
            name: "deadpool",
            sentiment: "positive"
        }],
        locations: [{
            name: "logan",
            sentiment: "none"
        }]
    },
    rating: null,
    crawled: "2017-03-05T00:45:28.810+02:00"
}],
totalResults: 3411,
moreResultsAvailable: 3410,
next: "/filterWebContent?token=XXXXX-XXXX-XXXX-    XXXXX&format=json&ts=1488464225907&q=deadpool&sort=social.facebook.likes&from=1&    sort=desc&size=1",
requestsLeft: 999911
}

Проблема:

Я пытаюсь извлечь некоторые поля из этого JSON.Однако некоторые поля сильно вложены, некоторые - одиночные.

Например, используя поле «posts», я могу получить значение для заголовка, автора, языковых ключей.Однако, используя следующий код, когда я пытаюсь получить значение для страны, местоположения, людей, организаций, настроений, я получаю нулевое значение для всех из них.Мой фрагмент кода выглядит следующим образом.

JsonArray postArray = result.getAsJsonObject().getAsJsonArray("posts");
System.out.println(postArray);
for(JsonElement o  : postArray) {
    System.out.println(o.getAsJsonObject().get("title"));  
    System.out.println(o.getAsJsonObject().get("author")); 
    System.out.println(o.getAsJsonObject().get("language"));   
    System.out.println(o.getAsJsonObject().get("country"));  
    System.out.println(o.getAsJsonObject().get("locations"));   
    System.out.println(o.getAsJsonObject().get("persons"));
    System.out.println(o.getAsJsonObject().get("organizations"));
    System.out.println(o.getAsJsonObject().get("sentiment"));
    System.out.println ("--------------------------------------");
}           

Как распечатать значения, соответствующие всем полям / клавишам?

1 Ответ

0 голосов
/ 28 мая 2018

Вы можете использовать рекурсию для вашего Java-объекта.

  • Проверьте ваше значение Является ли объект JSON.Если да, сделайте рекурсивный вызов
  • Иначе напечатайте ключ со значением
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...