Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用gson将json数据转换为java对象?_Java_Gson - Fatal编程技术网

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

如何使用gson将json数据转换为java对象?,java,gson,Java,Gson,我有一个json字符串。我想把它转换成java对象。我的实体类是Deneme.java Result变量存储jsonstring。我怎样才能完成这个过程 我得到一个错误:应该是BEGIN\u对象,但却是BEGIN\u数组 来自服务器的数据是 {"games": [ {"game":"Football","probability":0.74656546}, {"game":"Football","probability":0.2

我有一个
json
字符串。我想把它转换成java对象。我的实体类是
Deneme.java

Result
变量存储
json
string。我怎样才能完成这个过程

我得到一个错误:
应该是BEGIN\u对象,但却是BEGIN\u数组

来自服务器的数据是

 {"games":
       [   
            {"game":"Football","probability":0.74656546},
            {"game":"Football","probability":0.23432424},
            {"game":"Football","probability":0.2342342343}
       ]
 }
Deneme.java
is


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;
    }
}

转换到
Deneme

变,

private List<JsonObject> matches;
私有列表匹配;
对,


私人列表游戏

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

    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);
    }

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

结果是什么,粘贴conversionI get error的完整代码:不兼容的类型。需要Deneme,但“fromjson”,但推断为T。不存在类型变量的实例
    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);
    }
{"game":"Football","probability":0.74656546}
{"game":"Football","probability":0.23432424}
{"game":"Football","probability":0.2342342343}