简体   繁体   English

使用 gson 将 json 转换为 json 对象

[英]convert json to json object using gson

I have a class defined as follows -我有一个定义如下的类 -

public class info {
  private final string name;
  private final string add;
  private final Map<String, Skill> skills;
}

public class Skill {
  String subCategory;
  String proficiency;
}

JSON as  -
{
   "name": "abc",
   "add": "random",
   "skills": {
     "java": {
       "subCategory": "soft",
       "proficiency": "A"
     }
    "C#": {
       "subCategory": "soft",
       "proficiency": "B"
     }
  }
}

How can i convert this json to java object info?如何将此json转换为java对象信息? I have tried using gson library but running into multiple errors.我曾尝试使用 gson 库,但遇到多个错误。

The issue is because of map inside a class skills.问题是因为地图里面有一个类技能。 Not sure how to convert.不知道怎么转换。 i looked at example Converting JSON to Java object using Gson but its pretty simple no lists or map inside the class.我查看了使用 Gson 将 JSON 转换为 Java 对象的示例,但它非常简单,在类中没有列表或映射。

There are a few errors with your code, but after these are fixed it does work.您的代码有一些错误,但在修复这些错误后它确实可以工作。

  • You're trying to define strings with string instead of String您正在尝试使用string而不是String来定义字符串
  • You're defining your variables in info as final , and you're not defining them (removing the final keyword works)您将info的变量定义为final ,并且您没有定义它们(删除 final 关键字有效)
  • You're missing a , in your skills array in your JSON您在 JSON 的技能数组中缺少,

Below is an example which actually works:下面是一个实际工作的例子:

public class Main {
    public static void main(String[] args) {
        String json = "{\r\n"
                + "   \"name\": \"abc\",\r\n"
                + "   \"add\": \"random\",\r\n"
                + "   \"skills\": {\r\n"
                + "     \"java\": {\r\n"
                + "       \"subCategory\": \"soft\",\r\n"
                + "       \"proficiency\": \"A\"\r\n"
                + "     },\r\n"
                + "    \"C#\": {\r\n"
                + "       \"subCategory\": \"soft\",\r\n"
                + "       \"proficiency\": \"B\"\r\n"
                + "     }\r\n"
                + "  }\r\n"
                + "}";

        Info info = new Gson().fromJson(json, Info.class);
        System.out.println(info.getSkills());
    }

}

class Info {
    private String name;
    private String add;
    private Map<String, Skill> skills;

    public String getName() {
        return this.name;
    }

    public String getAdd() {
        return this.add;
    }

    public Map<String, Skill> getSkills() {
        return this.skills;
    }
}

class Skill {
    String subCategory;
    String proficiency;
}

I've also taken the liberty to rename info to Info since class names should start with a capital letter & added getters for the private variables.我还冒昧地将info重命名为Info因为类名应该以大写字母开头并为私有变量添加 getter。

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

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