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

标签 java android json gson

我需要将值从 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 );

我是 android 开发的新手,我可能忘记了一些东西,因为以下内容不起作用,有人可以帮助找出问题所在吗?

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

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

最佳答案

1。为您的 Json 创建您的 POJO 表示。

public class MapaNomes() {
    String name;
    String description;
    // etc

    public String getName() {
        return name;
    }

    // create your other getters and setters
}

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

2。阅读你的 file.json。把它变成对象

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

奖金

我认为您的 file.json 中可能有许多 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
}

关于java - 如何读取 json 文件,并使用 GSON 将其转换为 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33293403/

相关文章:

java - 想要将我的 ListView 与 Android Studio 中的文本链接

java - 安卓 + java.lang.NullPointerException : Attempt to invoke interface method

javascript - 当我在 jQuery 中执行 AJAX 调用时出现 JSON 错误

python - 来自 swagger-server 的 JSON 响应在单引号中收到,机器人框架验证失败,因为 json.loads 失败

android - Android 支持包的影响

json - 如何使用 JMESPath 获取键值对并将它们转换为对象数组

java - 如何将两个 JPanel 添加到 JFrame 的中心?

java - Neo4j 和 java : What does this error "NULL is not a keyed collection" mean?

java - 最快的集合包含 5-10 个整数的方法

android - 在相机之间切换,在 Nexus S 上崩溃