有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何读取json文件,并使用GSON将其转换为POJO

我需要将值从json文件传递到java类,json文件如下示例:

    {
        "id":1,
        "name":"Gold",
        "description":"Shiny!",
        "spriteId":1,
        "consumable":true,
        "effectsId":[1]
    },

我需要绘制地图,我做到了:

Items i = new Items();


Map<String, Items> mapaNomes = new HashMap<String, Items>();
mapaNomes.put("Gold",i);
mapaNomes.put("Apple",i );
mapaNomes.put("Clain Mail",i );

我是安卓开发的新手,我可能忘记了一些事情,因为下面的内容不起作用,有人能帮我找出问题所在吗

BufferedReader in  = new BufferedReader(new InputStreamReader(System.in));

Gson gson = new Gson(); 
Items Items = gson.fromJson((BufferedReader) mapaNomes, Items.class);

共 (1) 个答案

  1. # 1 楼答案

    一,。为Json创建POJO表示

    public class MapaNomes() {
        String name;
        String description;
        // etc
    
        public String getName() {
            return name;
        }
    
        // create your other getters and setters
    }
    

    我发现这个工具可以方便地将json转换为POJOhttp://www.jsonschema2pojo.org/

    二,。阅读你的文件。json。把它变成物体

    JsonReader reader = new JsonReader(new FileReader("file.json"));
    MapaNomes mapaNomes = new Gson().fromJson(reader, MapaNomes.class);
    

    奖金

    我认为你的文件中可能有很多json对象。例如:

    {
        "id":1,
        "name":"Gold",
        "description":"Shiny!",
        "spriteId":1,
        "consumable":true,
        "effectsId":[1]
    },
    ...
    {
        "id":999,
        "name":"Silver",
        "description":"Whatever!",
        "spriteId":808,
        "consumable":true,
        "effectsId":[2]
    },
    

    如果是这种情况,则可以执行以下操作:

    JsonReader reader = new JsonReader(new FileReader("file.json"));
    List<MapaNomes> mapaNomeses = new Gson().fromJson(
                                    reader, 
                                    new TypeToken<List<Review>>() {}.getType());
    
    Then you can do whatever you want with each and every one of them
    
    for (MapaNomes mapaNomes : mapaNomeses) {
        // whatever
    }