简体   繁体   English

在Java中使用GSON序列化JSON文件

[英]Serialize JSON file with GSON in java

I want to convert this JSON into objects in java: 我想将此JSON转换为java中的对象:

{
    "mapping": [
        {
            "boardPosition": {
                "row": 1,
                "col": 1
            },
            "nodeId": 3242324
        },
        {
            "boardPosition": {
                "row": 1,
                "col": 2
            },
            "nodeId": 432423
        },
        {
            "boardPosition": {
                "row": 1,
                "col": 3
            },
            "nodeId": 424324132
        }
    ]
}

this is how I created my java classes 这就是我创建Java类的方式

class MapeoWumpus {
    public mapp mapping;

    }

class mapp{
    public boardP boardPosition;
    public String nodeId;
}

class boardP{
    public int row;
    public int col;

}

and then when I try to convert my file like this 然后当我尝试像这样转换我的文件时

MapeoWumpus mapa=new MapeoWumpus();
mapa=gson.fromJson(filetext, MapeoWumpus.class);

I get a null object 我得到一个空对象

What can I do? 我能做什么?

EDIT: This is my entire code: 编辑:这是我的整个代码:

package parserjson;

import java.io.FileNotFoundException;
import java.util.*;
import com.google.gson.*;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) throws FileNotFoundException {
            String filetext;
            ParserJson parser=new ParserJson();
            Gson gson=new Gson();
            MapeoWumpus mapa=new MapeoWumpus();
            filetext=parser.leerArchivo("b1.json");
            mapa=gson.fromJson(filetext, MapeoWumpus.class);
    }

}

"leerArchivo" is just a method to get the json file, as you can see my json file is in a string variable “ leerArchivo”只是获取json文件的一种方法,因为您可以看到我的json文件位于字符串变量中

You should define instance variable mapp as array. 您应该将实例变量mapp定义为数组。 Because your JSON data seems to contain mapping array. 因为您的JSON数据似乎包含映射数组。

class MapeoWumpus {
    public mapp[] mapping;

}

Creating new MapeoWumpus in the below code is unnecessary 无需在以下代码中创建新的MapeoWumpus

MapeoWumpus mapa=new MapeoWumpus();
mapa=gson.fromJson(filetext, MapeoWumpus.class);

Just change it as follows 只需如下更改

MapeoWumpus mapa=gson.fromJson(filetext, MapeoWumpus.class);

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

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