简体   繁体   English

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

[英]How to use gson to convert json data to java object?

I have a json string.我有一个json字符串。 I want to convert it to java object.我想将其转换为 java 对象。 My entity class is Deneme.java .我的实体类是Deneme.java

Result variable stores json string. Result变量存储json字符串。 How can I make this process?我怎样才能完成这个过程?

I get an error: Expected BEGIN_OBJECT but was BEGIN_ARRAY我收到一个错误: Expected BEGIN_OBJECT but was BEGIN_ARRAY

Data coming from the server is,来自服务器的数据是,

 {"games":
       [   
            {"game":"Football","probability":0.74656546},
            {"game":"Football","probability":0.23432424},
            {"game":"Football","probability":0.2342342343}
       ]
 }

Deneme.java is, 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;
    }
}

My code is:我的代码是:

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

You need to have same name when you are converting to Deneme转换为Deneme时,您需要具有相同的名称

Change,改变,

private List<JsonObject> matches;

To,到,

private List<JsonObject> games;

With your current structure you could use something like :使用您当前的结构,您可以使用以下内容:

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

You should change private List<JsonObject> matches to private List<JsonObject> games .您应该将private List<JsonObject> matches更改为private List<JsonObject> games

The output is :输出是:

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

I think that in your case it could be better to create class Game and store list of Game objects inside your Deneme class, because now you are just storing JsonObject 's.我认为在你的情况下,最好在你的Deneme类中创建类Game和存储Game对象列表,因为现在你只是存储JsonObject的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM