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? I have tried using gson library but running into multiple errors.
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.
There are a few errors with your code, but after these are fixed it does work.
string
instead of String
info
as final
, and you're not defining them (removing the final keyword works),
in your skills array in your JSONBelow 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.