有 Java 编程相关的问题?

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

Java JSON解析器错误

我正在创建一个应用程序,它将向web服务器发送http请求。返回值将在json中。下面是json的样子

[//I used a tool to make it beautiful and easy to read.
  {
    "item_name": "Adame",
    "item_type": "Special",
    "item": "Chestplate",
    "item_min_lvl": "50",
    "enchantment": {
      "health": "0.3",
      "dam": "24%",
      "life": "0.1",
      "xp": "24%",
      "loot": "22%"
    },
    "def": "73"
  },
  {
    "item_name": "Sticks'",
    "item_type": "Unique",
    "item": "Stick",
    "item_min_lvl": "4",
    "enchantment": {
      "health": "0.6",
      "mana": "1",
      "dam": "12%",
      "life": "0.3",
      "xp": "17%",
      "loot": "17%"
    },
    "min_dam": "39",
    "max_dam": "34"
  },
  {
    "item_name": "Sword'",
    "item_type": "Unique",
    "item": "Sword",
    "item_min_lvl": "8",
    "enchantment": [], //colonm 30 is [
    "min_dam": "9",
    "max_dam": "10"
  }
]

你可以看到,数组中的数据是不同的。我得到了这个错误,Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 30。这是我的代码:

MyJSON[] data = gson.from(jsonString, MyJSON[].class);

class MyJSON {
    String item_name;
    String item_type;
    String item;
    String item_min_lvl;
    Enchantment enchantment;
    String min_dam;
    String max_dam;

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        builder.append("\nitem_name:").append(item_name);
        builder.append("\nitem_type:").append(item_type);
        builder.append("\nitem:").append(item);
        builder.append("\nitem_min_lvl:").append(item_min_lvl);

        builder.append("\n\nEnchantment Details:");
        builder.append("\nhealth:").append(enchantment.health);
        builder.append("\ndam:").append(enchantment.dam);
        builder.append("\nlife:").append(enchantment.life);
        builder.append("\nxp:").append(enchantment.xp);
        builder.append("\nloot:").append(enchantment.loot);
        return builder.toString();
    }
}

class Enchantment {
    String health;
    String dam;
    String life;
    String xp;
    String loot;
    String mana;
}

谁能帮我改进代码,让我的代码在不同的情况下解析json。提前谢谢。(顺便说一句,那不是我的web服务器,所以我不能用json做任何事情)


共 (3) 个答案

  1. # 1 楼答案

    这是一个有效的JSON,除非您添加注释只是为了显示问题所在

    注释不应该是JSON的一部分

    这是我在另一篇帖子Java - Json deserialize data []上分享给你的代码

    必须使用ArrayList<Map<String, Object>>,因为JSON字符串中的条目是不对称的。在这种情况下,不能将其转换为POJO

    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new FileReader(new File("resources/json2.txt")));
    String line = null;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }
    reader.close();
    
    Gson gson = new Gson();
    Type listType = new TypeToken<ArrayList<Map<String, Object>>>() {
    }.getType();
    ArrayList<Map<String, Object>> list = gson.fromJson(builder.toString(), listType);
    
    for (Map<String, Object> json : list) {
        for (String key : json.keySet()) {
            System.out.println(key + ":" + json.get(key));
        }
        System.out.println("===========");
    }
    

    输出:

    item_name:Adame
    item_type:Special
    item:Chestplate
    item_min_lvl:50
    enchantment:{health=0.3, dam=24%, life=0.1, xp=24%, loot=22%}
    def:73
    ===========
    item_name:Sticks'
    item_type:Unique
    item:Stick
    item_min_lvl:4
    enchantment:{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}
    min_dam:39
    max_dam:34
    ===========
    item_name:Sword'
    item_type:Unique
    item:Sword
    item_min_lvl:8
    enchantment:[]
    min_dam:9
    max_dam:10
    ===========
    

    编辑

    魔法回归

    enchantment:{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}. 
    

    例如,我怎样才能获得健康

    Type mapType = new TypeToken<Map<String, String>>() {
    }.getType();
    String string = "{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}";
    Map<String, String> map = new Gson().fromJson(string, mapType);
    for (String key : map.keySet()) {
        System.out.println(key + ":" + map.get(key));
    }
    

    输出:

    health:0.6
    mana:1
    dam:12%
    life:0.3
    xp:17%
    loot:17%
    
  2. # 2 楼答案

    可以在Gson的fromJson()方法中创建自定义列表类型,将其映射到POJO列表

    Type listType = new TypeToken<ArrayList<Enhancement>>() {}.getType();
    List<Enhancement> enhancements = new Gson().fromJson(jsonString, listType);
    

    你会得到一个List<Enhancement>

  3. # 3 楼答案

    基本上这行JSON

    "enchantment": [], //colonm 30 is [
    

    和你的POJO不匹配。您需要一个Enchantment对象,但JSON会给您一个数组。修复JSON,为enchantment对返回一个空的JSON对象或什么都不返回

    "enchantment": {}