簡體   English   中英

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

[英]Serialize JSON file with GSON 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
        }
    ]
}

這就是我創建Java類的方式

class MapeoWumpus {
    public mapp mapping;

    }

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

class boardP{
    public int row;
    public int col;

}

然后當我嘗試像這樣轉換我的文件時

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

我得到一個空對象

我能做什么?

編輯:這是我的整個代碼:

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”只是獲取json文件的一種方法,因為您可以看到我的json文件位於字符串變量中

您應該將實例變量mapp定義為數組。 因為您的JSON數據似乎包含映射數組。

class MapeoWumpus {
    public mapp[] mapping;

}

無需在以下代碼中創建新的MapeoWumpus

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

只需如下更改

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM