Kotlin с использованием Gson для десериализации локального json файла - PullRequest
1 голос
/ 26 мая 2020

Я хочу десериализовать локальный файл json с помощью Gson для создания recyclerview. Однако я получаю исключение IllegalStateException в строке ниже.

val homeFeed = gson.fromJson(json, HomeFeed::class.java)

Мой json файл сохраняется в папке с ресурсами и считаю, что программа правильно считывает данные, но каким-то образом не может преобразовать их в мой объект модели HomeFeed.

enter image description here

Ошибка ниже:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

NewsFragment.kt:

class NewsFragment : Fragment() {
    var arr = arrayListOf<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }

        read_json()

    }

    fun read_json(){
        var json : String? = null

        try {
            val inputStream: InputStream = context!!.assets.open("sample.json")

            json = inputStream.bufferedReader().use { it.readText() }

            val gson = GsonBuilder().create()
            val homeFeed = gson.fromJson(json, HomeFeed::class.java)

            activity?.runOnUiThread {
                worldnews.adapter = MainAdapter(homeFeed)
            }

        } catch (e: IOException) {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_news, container, false)

        view.worldnews.layoutManager = LinearLayoutManager(activity)

        return view
    }
}
class HomeFeed(val News: List<News>)

class News(val title: String, val description: String, val time: String, val link: String)

образец. json:

{
  News: [
    {
      title: "Intesa expected to approve state-backed loan for FCA -source",
      description: "Italy's biggest retail bank Intesa Sanpaolo is expected to give conditional approval at a board meeting on Tuesday to a state-guaranteed $6.3 billion euro three-year loan for Fiat Chrysler (FCA), a source close to the matter said.",
      time: "9:38am EDT",
      link: "https://www.reuters.com//article/health-coronavirus-fiat-chrylser-loan/intesa-expected-to-approve-state-backed-loan-for-fca-source-idUSS8N2B200A"
    },
    {
      title: "CANADA STOCKS-TSX opens higher on hopes of economic recovery",
      description: "Canada's main stock index rose in early trade on Monday as investors looked to an eventual economic recovery from the coronavirus with more countries scaling back lockdown measures.",
      time: "9:37am EDT",
      link: "https://www.reuters.com//article/canada-stocks/canada-stocks-tsx-opens-higher-on-hopes-of-economic-recovery-idUSL4N2D7257"
    },
    {
      title: "Bars, gyms reopen as Iceland exits emergency coronavirus alert",
      description: "Iceland eased its national alert against the coronavirus on Monday, allowing for public gatherings of up to 200 people and night clubs and gyms to reopen as the country nears complete recovery from the outbreak.",
      time: "9:20am EDT",
      link: "https://www.reuters.com//article/health-coronavirus-iceland/bars-gyms-reopen-as-iceland-exits-emergency-coronavirus-alert-idUSL8N2D71YX"
    },
    {
      title: "FOREX-Euro steadies in a big week for Europe's policymakers",
      description: "The euro steadied around the $1.09 level on Monday in a potentially big week for European policymakers as they debate the outlines of a recovery fund aimed at helping member nations.",
      time: "9:16am EDT",
      link: "https://www.reuters.com//article/global-forex/forex-euro-steadies-in-a-big-week-for-europes-policymakers-idUSL4N2D723P"
    },
    {
      title: "GLOBAL MARKETS-German survey fuels stock gains, euro investors eye EU summit",
      description: "Stocks gained modestly on Monday after a survey showed German business morale rebounded in May, while investors kept a close eye on escalating U.S.-China tensions in a thin trading session.",
      time: "9:11am EDT",
      link: "https://www.reuters.com//article/global-markets/global-markets-german-survey-fuels-stock-gains-euro-investors-eye-eu-summit-idUSL8N2D728Z"
    },
    {
      title: "EU must present united front to shield pandemic-hit banks -regulator",
      description: "European countries need to join forces to shield their banks from the coronavirus outbreak, one of the bloc's top regulators said on Monday, potentially using a 500 billion euro ($545 billion) EU recovery fund to do so.",
      time: "9:00am EDT",
      link: "https://www.reuters.com//article/health-coronavirus-banks-impact/eu-must-present-united-front-to-shield-pandemic-hit-banks-regulator-idUSL8N2D71GU"
    },
    {
      title: "UPDATE 3-With suitcase and bikini emojis, Spain urges tourists back from July",
      description: "* But few restaurants open and businesses fret for future (Adds foreign minister's tweet, edits)",
      time: "8:58am EDT",
      link: "https://www.reuters.com//article/health-coronavirus-spain/update-3-with-suitcase-and-bikini-emojis-spain-urges-tourists-back-from-july-idUSL8N2D70YL"
    },
    {
      title: "UPDATE 2-French tycoons close ranks to bolster Lagardere's defences",
      description: "* Lagardere shares jump 13% (Adds AMF regulatory filing, share reaction, Amber, source)",
      time: "8:30am EDT",
      link: "https://www.reuters.com//article/lagardere-ma-arnault/update-2-french-tycoons-close-ranks-to-bolster-lagarderes-defences-idUSL8N2D70JR"
    },
    {
      title: "Australian economy must come off COVID-19 'life support', PM to say",
      description: "Australia's economy must not become reliant on government stimulus, Prime Minister Scott Morrison will say on Tuesday, as Canberra unwinds state support and accelerates plans to spur growth.",
      time: "8:30am EDT",
      link: "https://www.reuters.com//article/health-coronavirus-australia-economy/australian-economy-must-come-off-covid-19-life-support-pm-to-say-idUSL8N2D728Q"
    },
    {
      title: "Talks on Lufthansa aid not concluded yet -ministry",
      description: "Negotiations on a government bailout for coronavirus-stricken airline Lufthansa are in their last phase but have not been concluded yet, a spokeswoman of the German economy ministry said on Monday.",
      time: "7:49am EDT",
      link: "https://www.reuters.com//article/health-coronavirus-lufthansa-ministry/talks-on-lufthansa-aid-not-concluded-yet-ministry-idUSL8N2D71ZN"
    },
    {
      title: "LIVE MARKETS-No signs of V-shaped German recovery, yet",
      description: "Welcome to the home for real-time coverage of European equity markets brought to you by Reuters stocks reporters. You can share your thoughts Joice Alves (joice.alves@thomsonreuters.com) and Julien Ponthus (julien.ponthus@thomsonreuters.com) in London and Stefano Rebaudo (stefano.rebaudo@thomsonreuters.com) in Milan.",
      time: "9:44am EDT",
      link: "https://www.reuters.com//article/europe-stocks/live-markets-no-signs-of-v-shaped-german-recovery-yet-idUSL8N2D72IQ"
    },
    {
      title: "LIVE MARKETS-Italian public debt? Concerns overblown",
      description: "Welcome to the home for real-time coverage of European equity markets brought to you by Reuters stocks reporters. You can share your thoughts Joice Alves (joice.alves@thomsonreuters.com) and Julien Ponthus (julien.ponthus@thomsonreuters.com) in London and Stefano Rebaudo (stefano.rebaudo@thomsonreuters.com) in Milan.",
      time: "5:58am EDT",
      link: "https://www.reuters.com//article/europe-stocks/live-markets-italian-public-debt-concerns-overblown-idUSL8N2D71H0"
    },
    {
      title: "European shares rise on recovery hopes, Bayer jumps",
      description: "European shares rose in thin trading on Monday, as optimism over reopening of countries and signs of more stimulus for the coronavirus-hit euro zone economy helped sentiment.",
      time: "4:55am EDT",
      link: "https://www.reuters.com//article/us-europe-stocks/european-shares-rise-on-recovery-hopes-bayer-jumps-idUSKBN2310PF"
    },
    {
      title: "UPDATE 1-European shares rise on recovery hopes, Bayer jumps",
      description: "* Lagardere jumps as LVMH's Arnault to buy stake (Adds comment, updates prices)",
      time: "4:52am EDT",
      link: "https://www.reuters.com//article/europe-stocks/update-1-european-shares-rise-on-recovery-hopes-bayer-jumps-idUSL4N2D71HR"
    },
    {
      title: "European shares rise in thin trading, Bayer jumps",
      description: "European shares rose in thin trading on Monday, as optimism over reopening of countries and signs of more stimulus for the battered euro zone economy helped sentiment.",
      time: "3:38am EDT",
      link: "https://www.reuters.com//article/europe-stocks/european-shares-rise-in-thin-trading-bayer-jumps-idUSL4N2D71DO"
    },
    {
      title: "LIVE MARKETS-Opening snapshot: Stoxx 600 positive, Bayer and Lagardere shine",
      description: "Welcome to the home for real-time coverage of European equity markets brought to you by Reuters stocks reporters. You can share your thoughts Joice Alves (joice.alves@thomsonreuters.com) and Julien Ponthus (julien.ponthus@thomsonreuters.com) in London and Stefano Rebaudo (stefano.rebaudo@thomsonreuters.com) in Milan.",
      time: "3:31am EDT",
      link: "https://www.reuters.com//article/europe-stocks/live-markets-opening-snapshot-stoxx-600-positive-bayer-and-lagardere-shine-idUSL8N2D70VC"
    },
    {
      title: "LIVE MARKETS-On the radar: LVMH, Lagardere, Bayer, Credit Suisse",
      description: "Welcome to the home for real-time coverage of European equity markets brought to you by Reuters stocks reporters. You can share your thoughts Joice Alves (joice.alves@thomsonreuters.com) and Julien Ponthus (julien.ponthus@thomsonreuters.com) in London and Stefano Rebaudo (stefano.rebaudo@thomsonreuters.com) in Milan.",
      time: "2:51am EDT",
      link: "https://www.reuters.com//article/europe-stocks/live-markets-on-the-radar-lvmh-lagardere-bayer-credit-suisse-idUSL8N2D70NT"
    },
    {
      title: "LIVE MARKETS-Morning call: higher opening in a subdued market",
      description: "Welcome to the home for real-time coverage of European equity markets brought to you by Reuters stocks reporters. You can share your thoughts Joice Alves (joice.alves@thomsonreuters.com) and Julien Ponthus (julien.ponthus@thomsonreuters.com) in London and Stefano Rebaudo (stefano.rebaudo@thomsonreuters.com) in Milan.",
      time: "1:33am EDT",
      link: "https://www.reuters.com//article/europe-stocks/live-markets-morning-call-higher-opening-in-a-subdued-market-idUSL8N2D70CD"
    },
    {
      title: "European stocks flat as U.S.-China woes weigh, but post weekly gain",
      description: "European shares closed unchanged on Friday although rising U.S.-China tensions hit Asia-exposed banks and luxury stocks, while hopes of a global recovery kept weekly gains intact for the main indexes.",
      time: "May 22 2020",
      link: "https://www.reuters.com//article/us-europe-stocks/european-stocks-flat-as-u-s-china-woes-weigh-but-post-weekly-gain-idUSKBN22Y0WD"
    },
    {
      title: "UPDATE 2-European stocks flat as U.S.-China woes weigh, but post weekly gain",
      description: "* Burberry gains after views on Asia recovery (Updates to market close)",
      time: "May 22 2020",
      link: "https://www.reuters.com//article/europe-stocks/update-2-european-stocks-flat-as-u-s-china-woes-weigh-but-post-weekly-gain-idUSL4N2D42K3"
    },
    {
      title: "GLOBAL MARKETS-Stocks gain as German survey fuels optimism; dollar firm",
      description: "Stocks edged higher on Monday after a survey showed German business morale rebounded in May, boosting optimism around economic re-openings, although caution prompted the dollar to snap a rare losing streak.",
      time: "5:46am EDT",
      link: "https://www.reuters.com//article/global-markets/global-markets-stocks-gain-as-german-survey-fuels-optimism-dollar-firm-idUSL8N2D71G7"
    },
    {
      title: "FOREX-U.S-China tensions boost dollar after weekly loss",
      description: "The U.S. dollar climbed on Monday after posting a rare weekly loss as investors flocked to the shelter of perceived safe-haven currencies on concerns about a growing standoff between the United States and China over civil liberties in Hong Kong.",
      time: "4:07am EDT",
      link: "https://www.reuters.com//article/global-forex/forex-u-s-china-tensions-boost-dollar-after-weekly-loss-idUSL8N2D70ZL"
    },
    {
      title: "GLOBAL MARKETS-Hong Kong shares ease on China-U.S. rift, dollar firms",
      description: "Hong Kong shares extended losses and a gauge of Asian stocks was largely subdued on Monday, after China's move to impose a new security law on Hong Kong heightened concerns about the future stability of the city and global trade prospects.",
      time: "2:44am EDT",
      link: "https://www.reuters.com//article/global-markets/global-markets-hong-kong-shares-ease-on-china-u-s-rift-dollar-firms-idUSL4N2D714S"
    },
    {
      title: "FOREX-Dollar on front foot as worries about Hong Kong stir risk aversion",
      description: "The dollar edged higher on Monday as worries about a standoff between the United States and China over civil liberties in Hong Kong fuelled demand for safe-haven currencies.",
      time: "2:12am EDT",
      link: "https://www.reuters.com//article/global-forex/forex-dollar-on-front-foot-as-worries-about-hong-kong-stir-risk-aversion-idUSL4N2D7163"
    },
    {
      title: "GLOBAL MARKETS-Asian shares reverse early gains, eyes on China-U.S. trade relations",
      description: "A gauge of Asian stocks pared early gains on Monday amid souring relations between China and the United States, with Hong Kong shares extending losses on mounting fears about future stability in the city.",
      time: "May 24 2020",
      link: "https://www.reuters.com//article/global-markets/global-markets-asian-shares-reverse-early-gains-eyes-on-china-u-s-trade-relations-idUSL4N2D70Q1"
    },
    {
      title: "FOREX-Dollar holds advantage as Hong Kong tensions test risk-wary investors",
      description: "The dollar edged higher against most Asian units on Monday as worries about a standoff between the United States and China over civil liberties in Hong Kong fuelled demand for safe-haven currencies.",
      time: "May 24 2020",
      link: "https://www.reuters.com//article/global-forex/forex-dollar-holds-advantage-as-hong-kong-tensions-test-risk-wary-investors-idUSL4N2D70J9"
    },
    {
      title: "China lowers yuan midpoint to weakest since 2008 global financial crisis",
      description: "China's central bank on Monday lowered its official yuan midpoint to the weakest since the 2008 global financial crisis, reflecting losses in the spot yuan on Friday after Beijing proposed a new national security law for Hong Kong.",
      time: "May 24 2020",
      link: "https://www.reuters.com//article/china-yuan/china-lowers-yuan-midpoint-to-weakest-since-2008-global-financial-crisis-idUSAZN0FOZ00"
    },
    {
      title: "GLOBAL MARKETS-Asian shares tick up, eyes on China-U.S. trade relations",
      description: "Asian shares started cautiously on Monday as central bank largesse globally boosted sentiment but rising trade tensions between the world's two biggest economies dulled risk appetite.",
      time: "May 24 2020",
      link: "https://www.reuters.com//article/global-markets/global-markets-asian-shares-tick-up-eyes-on-china-u-s-trade-relations-idUSL4N2D703S"
    },
    {
      title: "FOREX-Dollar edges higher as Hong Kong tensions fuel safe-haven demand",
      description: "The dollar edged higher on Monday as worries about a standoff between the United States and China over civil liberties in Hong Kong fuelled demand for safe-haven currencies.",
      time: "May 24 2020",
      link: "https://www.reuters.com//article/global-forex/forex-dollar-edges-higher-as-hong-kong-tensions-fuel-safe-haven-demand-idUSL4N2D60G4"
    },
    {
      title: "UPDATE 5-UK to introduce quarantine for international arrivals from June 8",
      description: "* Airlines and business groups say move sends wrong message (Adds France ready to impose reciprocal measures)",
      time: "May 22 2020",
      link: "https://www.reuters.com//article/health-coronavirus-britain/update-5-uk-to-introduce-quarantine-for-international-arrivals-from-june-8-idUSL8N2D417H"
    }
  ]
}

Ответы [ 2 ]

2 голосов
/ 26 мая 2020

Кажется, что ваш образец . json недействителен как JSON.

Ключевые строки, такие как News, title, description, time или link все должны быть указаны в кавычках: "News", "title", "description", "time" или "link".

1 голос
/ 26 мая 2020

Это потому, что вам нужно сначала получить News JSONArray из вашего ответа, а затем JSONArray вам нужно передать GSON, чтобы преобразовать ваш JSONArray в List модели HomeFeed.

var listType = object:TypeToken<List<HomeFeed>>() {}.type
var myModelList = gson.fromJson(json.toString(), listType)

итак, как только вы получите ответ

        json = inputStream.bufferedReader().use { it.readText() }
        val newsArray = json.getJSONArray("News")
        val gson = GsonBuilder().create()
        var listType = object:TypeToken<List<HomeFeed>>() {}.type
        var myModelList = gson.fromJson(json.toString(), listType)

        activity?.runOnUiThread {
            worldnews.adapter = MainAdapter(myModelList)
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...