Gson을 사용하여 로컬 json 파일을 역 직렬화하는 Kotlin

오비 미노루

Gson을 사용하여 로컬 json 파일을 역 직렬화하여 recyclerview를 만들고 싶습니다. 그러나 아래 줄에 IllegalStateException이 발생합니다.

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

내 json 파일은 자산 폴더에 저장되며 프로그램이 데이터를 잘 읽지 만 어떻게 든 내 HomeFeed 모델 개체로 변환 할 수 없다고 생각합니다.

여기에 이미지 설명 입력

아래 오류 :

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)

sample.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 ([email protected]) and Julien Ponthus ([email protected]) in London and Stefano Rebaudo ([email protected]) 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 ([email protected]) and Julien Ponthus ([email protected]) in London and Stefano Rebaudo ([email protected]) 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 ([email protected]) and Julien Ponthus ([email protected]) in London and Stefano Rebaudo ([email protected]) 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 ([email protected]) and Julien Ponthus ([email protected]) in London and Stefano Rebaudo ([email protected]) 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 ([email protected]) and Julien Ponthus ([email protected]) in London and Stefano Rebaudo ([email protected]) 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"
    }
  ]
}
오류

sample.json 이 JSON으로 유효하지 않은 것 같습니다 .

키 문자열과 같은 같은 News, title, description, time또는 link모두 인용한다 : "News", "title", "description", "time"또는 "link".

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

GSON 또는 Jackson을 사용하여 일반 인수를 사용하여 JSON을 클래스로 역 직렬화

분류에서Dev

Gson을 사용하여 JSON을 HashMAp <String, POJO>로 역 직렬화하지 못함

분류에서Dev

C #으로 JSON 파일을 역 직렬화하는 방법

분류에서Dev

작동하지 않는 Gson을 사용하여 json 역 직렬화

분류에서Dev

Gson을 사용하여 매핑 할 json 배열 역 직렬화

분류에서Dev

Gson을 사용하여 Json에서 Map 역 직렬화

분류에서Dev

GSON을 사용하여 객체의 JSON 배열 역 직렬화

분류에서Dev

Newtosoft Json을 사용하여 Json을 null로 역 직렬화

분류에서Dev

JSON.NET C #을 사용하여 내부 클래스가있는 json 파일로 역 직렬화

분류에서Dev

JavaScriptSerializer를 사용하여 JSON을 튜플으로 역 직렬화하는 방법

분류에서Dev

Jackson을 사용하여 JAVA 클래스를 대상으로하는 JSON 직렬화 및 역 직렬화

분류에서Dev

C #을 사용하여 클래스로 JSON 역 직렬화

분류에서Dev

JSON.net을 사용하여 동적으로 역 직렬화

분류에서Dev

GSON을 사용하여 평면화 된 JSON 키를 적절한 개체로 역 직렬화

분류에서Dev

Jackson을 사용하여 JSON 배열을 단일 연결 목록으로 역 직렬화하는 방법

분류에서Dev

ServiceStack을 사용하여 json을 여러 DataContract 중 하나로 역 직렬화하는 방법

분류에서Dev

JSON.NET을 사용하여 파생 클래스로 역 직렬화

분류에서Dev

Gson을 사용하여 POJO를 Json으로 직렬화

분류에서Dev

System.Runtime.Serialization.Json을 사용하여 JSON 배열을 목록으로 역 직렬화하는 방법

분류에서Dev

System.Text.Json을 사용하여 동적 속성을 포함하는 클래스로 JSON 역 직렬화

분류에서Dev

Newtonsoft.Json을 사용하여 C #에서 중첩 배열로 json을 역 직렬화하는 방법

분류에서Dev

GSON를 사용하여 알 수없는 원시적 인 JSON 속성 유형을 역 직렬화하는 방법

분류에서Dev

공백을 포함하는 열거 형을 사용하여 Json을 NJsonSchema 생성 객체로 역 직렬화

분류에서Dev

클래스 이름을 동적 값으로 사용하여 json을 역 직렬화하는 방법

분류에서Dev

Newtonsoft.JSON을 사용하여 C #으로 Json 문자열 역 직렬화

분류에서Dev

동적 키를 사용하여 JSON을 사전으로 역 직렬화

분류에서Dev

JSON 문자열을 객체로 역 직렬화하는 방법

분류에서Dev

Newtonsoft.Json을 사용하여 이름을 값으로 역 직렬화

분류에서Dev

Jackson을 사용하여 JSON 배열을 매핑으로 역 직렬화

Related 관련 기사

  1. 1

    GSON 또는 Jackson을 사용하여 일반 인수를 사용하여 JSON을 클래스로 역 직렬화

  2. 2

    Gson을 사용하여 JSON을 HashMAp <String, POJO>로 역 직렬화하지 못함

  3. 3

    C #으로 JSON 파일을 역 직렬화하는 방법

  4. 4

    작동하지 않는 Gson을 사용하여 json 역 직렬화

  5. 5

    Gson을 사용하여 매핑 할 json 배열 역 직렬화

  6. 6

    Gson을 사용하여 Json에서 Map 역 직렬화

  7. 7

    GSON을 사용하여 객체의 JSON 배열 역 직렬화

  8. 8

    Newtosoft Json을 사용하여 Json을 null로 역 직렬화

  9. 9

    JSON.NET C #을 사용하여 내부 클래스가있는 json 파일로 역 직렬화

  10. 10

    JavaScriptSerializer를 사용하여 JSON을 튜플으로 역 직렬화하는 방법

  11. 11

    Jackson을 사용하여 JAVA 클래스를 대상으로하는 JSON 직렬화 및 역 직렬화

  12. 12

    C #을 사용하여 클래스로 JSON 역 직렬화

  13. 13

    JSON.net을 사용하여 동적으로 역 직렬화

  14. 14

    GSON을 사용하여 평면화 된 JSON 키를 적절한 개체로 역 직렬화

  15. 15

    Jackson을 사용하여 JSON 배열을 단일 연결 목록으로 역 직렬화하는 방법

  16. 16

    ServiceStack을 사용하여 json을 여러 DataContract 중 하나로 역 직렬화하는 방법

  17. 17

    JSON.NET을 사용하여 파생 클래스로 역 직렬화

  18. 18

    Gson을 사용하여 POJO를 Json으로 직렬화

  19. 19

    System.Runtime.Serialization.Json을 사용하여 JSON 배열을 목록으로 역 직렬화하는 방법

  20. 20

    System.Text.Json을 사용하여 동적 속성을 포함하는 클래스로 JSON 역 직렬화

  21. 21

    Newtonsoft.Json을 사용하여 C #에서 중첩 배열로 json을 역 직렬화하는 방법

  22. 22

    GSON를 사용하여 알 수없는 원시적 인 JSON 속성 유형을 역 직렬화하는 방법

  23. 23

    공백을 포함하는 열거 형을 사용하여 Json을 NJsonSchema 생성 객체로 역 직렬화

  24. 24

    클래스 이름을 동적 값으로 사용하여 json을 역 직렬화하는 방법

  25. 25

    Newtonsoft.JSON을 사용하여 C #으로 Json 문자열 역 직렬화

  26. 26

    동적 키를 사용하여 JSON을 사전으로 역 직렬화

  27. 27

    JSON 문자열을 객체로 역 직렬화하는 방법

  28. 28

    Newtonsoft.Json을 사용하여 이름을 값으로 역 직렬화

  29. 29

    Jackson을 사용하여 JSON 배열을 매핑으로 역 직렬화

뜨겁다태그

보관