如何使用 gson 将 json 数据转换为 java 对象?

我有一个json字符串。我想将其转换为 java 对象。我的实体类是Deneme.java.


Result变量存储json字符串。我怎样才能做这个过程?


我收到一个错误:Expected BEGIN_OBJECT but was BEGIN_ARRAY


来自服务器的数据是,


 {"games":

       [   

            {"game":"Football","probability":0.74656546},

            {"game":"Football","probability":0.23432424},

            {"game":"Football","probability":0.2342342343}

       ]

 }

Deneme.java是,



import com.google.gson.JsonObject;

import org.json.JSONArray;


import java.util.List;


public class Deneme {


    private List<JsonObject> matches;


    public List<JsonObject> getMatches() {

        return matches;

    }


    public void setMatches(List<JsonObject> matches) {

        this.matches = matches;

    }

}

我的代码是:


Gson gson = new Gson();

Deneme obj = gson.fromJson(result, Deneme.class);


拉风的咖菲猫
浏览 105回答 2
2回答

手掌心

使用您当前的结构,您可以使用以下内容:&nbsp; &nbsp; public class Deneme {&nbsp; &nbsp; &nbsp; &nbsp; private List<JsonObject> games;&nbsp; &nbsp; &nbsp; &nbsp; public List<JsonObject> getMatches() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return games;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public void setMatches(List<JsonObject> games) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.games = games;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Deneme deneme = new Gson().fromJson(json, Deneme.class);&nbsp; &nbsp; &nbsp; &nbsp; deneme.getMatches().forEach(System.out::println);&nbsp; &nbsp; }您应该更改private List<JsonObject> matches为private List<JsonObject> games.输出是:{"game":"Football","probability":0.74656546}{"game":"Football","probability":0.23432424}{"game":"Football","probability":0.2342342343}我认为在你的情况下,在你的类中创建类Game和存储Game对象列表可能会更好Deneme,因为现在你只是存储JsonObject's.

互换的青春

当您转换为时,您需要具有相同的名称Deneme改变,private&nbsp;List<JsonObject>&nbsp;matches;至,private List<JsonObject> games;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java