使用Jackson

时间:2016-04-25 16:39:01

标签: web-services rest jersey jackson jersey-client

我编写了一个网络服务,并托管在以下网址http://192.168.2.34:8081/MyWebService/facility/university

此Web服务以JSON格式的响应是:

{
  "university": [
    {
      "emailOfPrincipal": "prin1@gmail.com",
      "labLists": [
        {
          "instrumentLists": [
            {
              "instrumentId": "1",
              "instrumentName": "Instrument 1"
            },
            {
              "instrumentId": "2",
              "instrumentName": "instrument 2"
            }
          ],
          "labId": "11",
          "labName": "Lab 11"
        },
        {
          "instrumentLists": [
            {
              "instrumentId": "3",
              "instrumentName": "instrument 3"
            },
            {
              "instrumentId": "4",
              "instrumentName": "instrument 4"
            }
          ],
          "labId": "22",
          "labName": "Lab 22"
        }
      ],
      "univAddress": "Kolkata",
      "univId": "111",
      "univName": "University 111",
      "univPrincipalName": "Principal 1"
    },
    {
      "emailOfPrincipal": "prin2@gmail.com",
      "labLists": [
        {
          "instrumentLists": [
            {
              "instrumentId": "5",
              "instrumentName": "Instrument 5"
            },
            {
              "instrumentId": "6",
              "instrumentName": "Instrument 6"
            }
          ],
          "labId": "33",
          "labName": "Lab 33"
        },
        {
          "instrumentLists": [
            {
              "instrumentId": "7",
              "instrumentName": "Instrument 7"
            },
            {
              "instrumentId": "8",
              "instrumentName": "Instrument 8"
            }
          ],
          "labId": "44",
          "labName": "Lab 44"
        }
      ],
      "univAddress": "Bangalore",
      "univId": "222",
      "univName": "University 222",
      "univPrincipalName": "Principal 2"
    },
    {
      "emailOfPrincipal": "prin3@gmail.com",
      "labLists": [
        {
          "instrumentLists": [
            {
              "instrumentId": "9",
              "instrumentName": "Instrument 9"
            },
            {
              "instrumentId": "10",
              "instrumentName": "Instrument 10"
            }
          ],
          "labId": "55",
          "labName": "Lab 55"
        },
        {
          "instrumentLists": [
            {
              "instrumentId": "11",
              "instrumentName": "Instrument 11"
            },
            {
              "instrumentId": "12",
              "instrumentName": "Instrument 12"
            }
          ],
          "labId": "66",
          "labName": "Lab 66"
        }
      ],
      "univAddress": "Hyderabad",
      "univId": "333",
      "univName": "University 333",
      "univPrincipalName": "Principal 3"
    }
  ]
}

我正在尝试使用jackson api将JSON数据转换为Java对象。但是得到一个错误。 我的Java对象是:

University.java

public class University {
    private int univId;
    private String univName;
    private String univAddress;
    private String univPrincipalName;
    private String emailOfPrincipal;
    private List<Laboratory> labLists = new ArrayList<>();

    //... Getter and Setter Methods...
}

Laboratory.java

public class Laboratory {

    private int labId;
    private String labName;
    private List<Instruments> instrumentLists = new ArrayList<>();
    //... Getter and Setter Methods...
}

Instruments.java

public class Instruments {

    private int instrumentId;
    private String instrumentName;
    private String bookingStatus;
    private Date bookingFrom;
    private Date bookingTo;
    private Date requestedTime;

    //... Getter and Setter Methods...
}

客户写的是:

public class ParseJSONData {

    public static void main(String[] args) throws ClientProtocolException, IOException {
        String URL = "http://192.168.2.34:8081/MyWebService/facility/university";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(URL);
        HttpResponse response = httpclient.execute(httpget);
        // System.out.println(response);

        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);

        ObjectMapper mapper = new ObjectMapper();

        University universities = mapper.readValue(result, University.class);
        System.out.println(universities.getEmailOfPrincipal());
    }

我得到的错误是

Exception in thread "main" org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "university" (Class University), not marked as ignorable
 at [Source: java.io.StringReader@100edc0; line: 1, column: 16] (through reference chain: University["university"])

我知道我的JSON数据正在返回大学列表。但是如何映射列表中的那些我不知道。任何形式的帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以添加父类

public class UniversityList {
    private List<University> university;
    //... Getter and Setter Methods...
}

和我们一样:

ObjectMapper mapper = new ObjectMapper();
UniversityList list = mapper.readValue(json, UniversityList.class));
University university = list.getUniversity().get(0)

其他选项是为University

创建自定义反序列化程序

以下是演示:

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(University.class, new UniversityDeserializer());
    mapper.registerModule(module);
    University university = mapper.readValue(json, University.class);
}

public static  class UniversityDeserializer extends JsonDeserializer<University> {
    private ObjectMapper unmodifiedMapper = new ObjectMapper();
    @Override
    public University deserialize(JsonParser p, DeserializationContext ctxt)
                                                                throws IOException{
        JsonNode node = p.readValueAsTree();
        JsonNode array = node.get("university");
        if (array != null && array.isArray()){
            JsonNode uniNode =  array.get(0);
            return unmodifiedMapper.treeToValue(uniNode, University.class);
        }
        return null;
    }
}