---
title: "fastjson-自省支持"
author: "helloklzs"
date: "2011-09-08T22:22:26Z"
tags: []
categories: ["编程语言"]
slug: "fastjson"
draft: false
lastmod: "2011-09-08T22:22:26Z"
id: 1168866
url: "https://helloklzs.iteye.com/blog/1168866"
---

在标准中，将对象序列化为JSON文本之后，就丢失了类型信息。虽然fastjson能够支持parse时传入Class来实现类型的识别，但是这个有局限性，在fastjson 1.1.3之后，完善支持一个特性，就是自省。

示例代码
public void test_0() throws Exception {
    Entity entity = new Entity(3, "jobs");
    String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName);
    System.out.println(text);
 
    Entity entity2 = (Entity) JSON.parseObject(text); //自动识别
 
    Assert.assertEquals(entity.getId(), entity2.getId());
    Assert.assertEquals(entity.getName(), entity2.getName());
}
 
public static class Entity {
    private int    id;
    private String name;
    public Entity(){
    }
    public Entity(int id, String name){
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
输出的JSON文本
{
    "@type":"com.alibaba.json.test.bvt.WriteClassNameTest$Entity",  // 输出时带上类型信息
    "id":3,
    "name":"jobs"
}
Labels:
