I am very new to java and just started with json...
I have the following json file:
"step1": {
"version": 1,
"items": {
"run": false,
"jump": true
}
},
"step2": {
"version": "None",
"items": {
"happy": true,
"sad": false
}
}
I am using Gson in my main like this:
Gson gs = new Gson();
Content tmp = gs.fromJson(<json string>, Content.class);
my class:
public class Content {
@SerializedName("step1")
private Step step1;
@SerializedName("step2")
private Step step2;
}
each step class:
public class Step{
@SerializedName("version")
private String version;
@SerializedName("items")
???????
}
as you can see the "?????" part is what I am trying to understand - How can I convert the items without needing to know the field name..? meaning to a HashMap/another iterable object..? can I initialize using a method..?
I have tried creating an Item class with a constructor but I do not understand how to use it in this case..
You can use a Map<String, Boolean>
to store your items. You Step
class can be something, like this:
public class Step {
private String version;
private Map<String, Boolean> items;
}
Then you can add your values to the Map:
Step step = new Step();
step.setVersion("None");
Map<String, Boolean> items = new HashMap<>();
items.put("happy", Boolean.TRUE);
items.put("sad", Boolean.FALSE);
step.setItems(items);
Hope that helps you.
The solution that worked for me is:
public class Step{
@SerializedName("version")
private String version;
@SerializedName("items")
private HashMap<String,Boolean> items;
}
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.