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

刀具10

我有一个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);
迈克尔

使用您当前的结构,您可以使用以下内容:

    public class Deneme {

        private List<JsonObject> games;

        public List<JsonObject> getMatches() {
            return games;
        }

        public void setMatches(List<JsonObject> games) {
            this.games = games;
        }
    }

    public static void main(String[] args) {

        Deneme deneme = new Gson().fromJson(json, Deneme.class);

        deneme.getMatches().forEach(System.out::println);
    }

您应该更改private List<JsonObject> matchesprivate List<JsonObject> games.

输出是:

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

我认为在你的情况下,在你的类中创建类Game和存储Game对象列表可能会更好Deneme,因为现在你只是存储JsonObject's.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章