Skip to content
This repository has been archived by the owner on Oct 23, 2024. It is now read-only.

productJson.toJavaObject(Product.class)不能反序列化XMLGregorianCalendar类型,但是JSON.parseObject(productJson().toJSONString(),Product.class) 可以 #1023

Closed
tianhao opened this issue Feb 13, 2017 · 1 comment
Milestone

Comments

@tianhao
Copy link

tianhao commented Feb 13, 2017

1.2.24版本
productJson 是mybatis从数据库jsonb字段的数据,JSONObject类型,通过productJson.toJSONString()后的字符串根平常json字符串一样。

本来想有了productJson之后可以直接调用productJson .toJavaObject(Product.class)反序列化成Product对象的,但是报错:com.alibaba.fastjson.JSONException: can not cast to : javax.xml.datatype.XMLGregorianCalendar

而通过JSON.parseObject(productJson().toJSONString(),Product.class) 切可以反序列化成功。
虽然可以做到,但是用法上不如前者。

@tianhao
Copy link
Author

tianhao commented Mar 5, 2017

补充一个测试案例:

    @Test
    public void testXMLGregorianCalendar() {
        Date now = new Date();
        XMLGregorianCalendar calendar = UnitBuilder.convertToXMLGregorianCalendar(now);
        String jsonString = JSON.toJSONString(calendar);
        // success
        calendar = JSON.parseObject(jsonString, XMLGregorianCalendar.class);

        Object toJSON1 = JSON.toJSON(calendar); // debug看到是 Long 类型
        // 所以这里会报错:
        // error: java.lang.ClassCastException: java.lang.Long cannot be cast to com.alibaba.fastjson.JSONObject
        //JSONObject jsonObject = (JSONObject) JSON.toJSON(calendar);
        // 所以 这里肯定会报错, 因为 jsonObject 不是JSONObject类型
        //calendar = jsonObject.toJavaObject(XMLGregorianCalendar.class);

        List<XMLGregorianCalendar> calendarList = new ArrayList<>();
        calendarList.add(calendar);
        calendarList.add(calendar);
        calendarList.add(calendar);

        Object toJSON2 = JSON.toJSON(calendarList); // debug 看到是 JSONArray 类型

        // success: 通过 JSONArray.parseArray 方法可以正确转换
        JSONArray jsonArray = (JSONArray) JSON.toJSON(calendarList);
        jsonString = jsonArray.toJSONString();
        List<XMLGregorianCalendar> calendarList1 = JSONArray.parseArray(jsonString, XMLGregorianCalendar.class);

        // 通过 jsonArray.toJavaList 无法转换
        // error: com.alibaba.fastjson.JSONException: can not cast to : javax.xml.datatype.XMLGregorianCalendar
        List<XMLGregorianCalendar> calendarList2 = jsonArray.toJavaList(XMLGregorianCalendar.class);
        System.out.println("DONE");
    }

@wenshao wenshao added this to the 1.2.29 milestone Mar 11, 2017
wenshao added a commit that referenced this issue Mar 11, 2017
@wenshao wenshao closed this as completed Mar 16, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants