将嵌套类的java对象转换为Json

时间:2016-05-17 20:21:58

标签: java json jackson

我一直在尝试从具有嵌套类的java对象/类创建json。但是只有顶级类在Json中输出。我想从Web服务应用程序返回json,或者将json转换为具有嵌套类的java对象

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("\nReceived Request for json data what happens now ! \n");
    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"
     }
    }

1 个答案:

答案 0 :(得分:0)

杰克逊序列化对象和实例属性。您的类将其所有成员定义为_class_members - 即静态。这意味着无论从您的类中实例化多少个对象,每个静态属性只有一个值。设置其中一个属性值的每一段代码都会为读取它的每一段代码改变它。

也许您已将属性设置为静态,因为您的PersonalInfo嵌套类类是静态的。从PersonalInfo类中删除static修饰符。更好的是,使它成为顶级类并删除静态修饰符。

抛开:因为您的代码将在Web应用程序中使用,所以您的类将由许多线程实例化。在诸如此类的数据类中使用非最终静态成员 非常非常危险 。您的所有客户都将共享相同的数据。