I have been trying to create json from a java object / class that has a nested class. However only the top level class is output in Json. I want to return json from a web services application or alternatively covert json to a java object with nested classes
public class JsonData {
static String firstName;
static String lastName;
static String streetName;
static String cityName;
static String stateName;
static PersonalInfo personalInfo = new PersonalInfo();
// typical set and get followed by the nested class
static class PersonalInfo {
String height;
String weight;
String eyeColor;
String favoriteColor;
// getter's and setters for this class
}
}
// in a separate method that handles the web service request set the values...
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody String sendJsonSample() throws JsonGenerationException {
ObjectMapper jsonMapper = new ObjectMapper();
System.out.println("
Received Request for json data what happens now !
");
JsonData jsonData = new JsonData();
jsonData.setCityName("New York");
jsonData.setFirstName("Fred");
jsonData.setLastName("Smith");
jsonData.setStateName("NY");
jsonData.setStreetName("Broadway");
JsonData.personalInfo.setEyeColor("Green");
JsonData.personalInfo.setFavoriteColor("Yellow");
JsonData.personalInfo.setHeight("SixFeet");
JsonData.personalInfo.setWeight("180");
// now convert to json with the following
try {
String json = jsonMapper.writeValueAsString(jsonData);
return json;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "ERROR"
}
// if I use a browser to my controller http://localhost:8080/json the json returned to my web services call only includes the top or outer level class
{
stateName: "NY",
firstName: "Fred",
lastName: "Smith",
streetName: "Broadway",
cityName: "New York"
}
// I would have expected or I want I should say
{
"state": "NY",
"firstName": "Fred",
"lastName": "Smith",
"streetName": "Broadway",
"cityName": "New York",
"PersonalInfo": {
"EyeColor":"Green",
"FavoriteColor": "Yellow",
"height":"SixFeet",
"Weight":"189"
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…