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

时间:2019-04-19 11:16:45

标签: java gson

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

2 个答案:

答案 0 :(得分:0)

转换为Deneme时,您需要使用相同的名称

更改

private List<JsonObject> matches;

收件人

private List<JsonObject> games;

答案 1 :(得分:0)

根据您当前的结构,您可以使用类似:

    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> matches更改为private List<JsonObject> games

输出为:

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

我认为在您的情况下,最好创建类Game并将Game对象的列表存储在Deneme类中,因为现在您只存储{{1} }。