FastJson toJSONString 解析报错

作者: 猫爪 | 来源:发表于2017-07-19 17:29 被阅读780次
  • 废话不多说直接看代码

  public class MessageBody {
   
    private String who;
   
    private String are;
  
    private static MessageContent you;

    public DRMessageBody(){  }

   //转Json
    public String toJson(){
        String json = JSON.toJSONString(this);

        if(json ==null){
            throw new RuntimeException("json parese erro");
        }
        return json;
    }

    public int getLengthOfByte(){
        String json = toJson();
        int num = -1;
        num = json.getBytes().length;
        if(num==-1){
            new RuntimeException("Messagebody of json length is error!");
        }
        return num;
    }

}

上面的代码 用下面的 测试

MessageBody body = JSON.parseObject(Json, MessageBody.class);

String result = JSON.toJSONString(body);

 System.out.println(body);

 System.out.println(result);

报错内容很多 就不一一列出来了

ava.lang.StackOverflowError
    at java.util.IdentityHashMap.containsKey(IdentityHashMap.java:349)
    at com.alibaba.fastjson.serializer.JavaBeanSerializer.writeReference(JavaBeanSerializer.java:395)
    at com.alibaba.fastjson.serializer.ASMSerializer_2_DRMessageContent.write(Unknown Source)
    at com.alibaba.fastjson.serializer.ASMSerializer_1_DRMessageBody.write(Unknown Source)

做个分析 FastJson 在使用 toJSONString 会使用 写入操作,而 我的类里面有这样一个方法 public int getLengthOfByte()
这样FastJson 就会认为 这个类 有一个 lengthOfByte 的属性,于是就出现了异常,解决方法

@JSONType(ignores = "lengthOfByte")
public class DRMessageBody {

  public int getLengthOfByte(){
        String json = toJson();
        int num = -1;
        num = json.getBytes().length;
        if(num==-1){
            new RuntimeException("Messagebody of json length is error!");
        }
        return num;
    }
}

使用 @JSONType(ignores = "lengthOfByte") 忽略 这个属性 就可以了

相关文章

网友评论

    本文标题:FastJson toJSONString 解析报错

    本文链接:https://www.haomeiwen.com/subject/loalkxtx.html