使用特定语法将Java对象转换为JSON

时间:2016-04-01 08:50:09

标签: java json serialization

我想将Java对象转换为JSON字符串。让我们说对象看起来像这样:

public class User{
    private Long id;
    private String firstName;
}

json应该是这样的:

{
    "inputFields":[
        {
            "name":"id",
            "value":"123"
        },
        {
            "name":"firstName",
            "value":"George"
        }
    ]
}

试图使用杰克逊,但看起来它没有提供这种序列化。

3 个答案:

答案 0 :(得分:2)

杰克逊可以使用自定义序列化程序,您可以控制生成输出。 以下是执行此操作的步骤:

注释您的POJO以使用自定义序列化程序

@JsonSerialize(using = CustomSerializer.class)
static class User{
    public Long id;
    public String firstName;

    public User(Long id, String firstName) {
        this.id = id;
        this.firstName = firstName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

声明序列化器

static class CustomSerializer extends JsonSerializer{

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeArrayFieldStart("inputFields");

        Field[] fields = value.getClass().getDeclaredFields();

        for (Field field : fields) {
            try {
                field.setAccessible(true);
                jgen.writeStartObject();
                jgen.writeObjectField("name", field.getName());
                jgen.writeObjectField("value", field.get(value));
                jgen.writeEndObject();
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }

        }

        jgen.writeEndArray();
        jgen.writeEndObject();
    }
}

一个简单的测试

public static void main(String[] args) throws JsonProcessingException {
    User user = new User(1L, "Mike");
    ObjectMapper om = new ObjectMapper();
    om.writeValueAsString(user);
    System.out.println(om.writeValueAsString(user));
}

输出将是

{"inputFields":[{"name":"id","value":1},{"name":"firstName","value":"Mike"}]}

答案 1 :(得分:0)

创建InputFields类并在转换为json之前将User对象数据移动到它。

编辑:InputFields类显然与所需的json结果具有相同的结构。

答案 2 :(得分:0)

只是斯堪的纳维亚答案的一个例子,但我更喜欢dumitru实现CustomSerializer的方法。

  1. 创建一个InputField类

    public class InputField {
    
        private String name;
        private String value;
    
        public String getValue() {
            return value;
        }
    
        public void setValue(String value) {
            this.value = value;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    
  2. 解析用户

    public static List<InputField> parseInputFields(Object model) {
        List<InputField> inputFields = new ArrayList<InputField>();
    
        Field[] field = model.getClass().getDeclaredFields();
        try {
            for (int j = 0; j < field.length; j++) {
    
                InputField inputField = new InputField();
    
                inputField.setName(field[j].getName());
                inputField.setValue(String.valueOf(field[j].get(model));
    
                inputFields.add(inputField);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    
        return inputFields;
    } 
    
  3. 测试

    public static void main(String[] args) throws JsonProcessingException {
        User user = new User(1L, "Mike");
    
        Map<String, Object> tmpMap=new HashedMap();
        tmpMap.put("inputFields", parseInputFields(user));
    
        ObjectMapper om = new ObjectMapper();
        System.out.println(om.writeValueAsString(tmpMap));
    }