简体   繁体   English

杰克逊序列化没有字段名称

[英]Jackson Serialize without field name

This is slight extension of my previous question . 这是我先前问题的轻微扩展。 So based on dambros' answer, the json now looks like: 因此,基于dambros的答案,json现在看起来像:

"Foo": {
    "title": {
        "type": "title",
        "value": "...",
        "variable": "..."
    },
    "message": {
        "type": "message",
        "value": "...",
        "variable": "..."
    }
}

But what I really want is: 但是我真正想要的是:

"Foo": [
{
    {
        "type": "title",
        "value": "...",
        "variable": "..."
    },
    {
        "type": "message",
        "value": "...",
        "variable": "..."
    }
}
]

Is there any way to write the Foo field as an array and also not display the variable names as fields (ie remove "title" : ). 有什么方法可以将Foo字段写为数组,也不能将变量名称显示为字段(即删除"title" :

That is not valid JSON, however this is: 那不是有效的JSON,但是这是:

{
    "Foo": [
        {
            "type": "title",
            "value": "...",
            "variable": "..."
        },
        {
            "type": "message",
            "value": "...",
            "variable": "..."
        }
    ]
}

This is a JSON object with a single field named Foo that is an array of objects. 这是一个JSON对象,具有一个名为Foo字段,该字段是对象数组。

You should read the JSON spec . 您应该阅读JSON规范


Alternatively, if you have a List<Foo> , you can serialize the list directly, giving you a JSON array as the root, instead of a JSON object as the root: 或者,如果您具有List<Foo> ,则可以直接序列化列表,以JSON数组作为根,而不是JSON对象作为根:

[
    {
        "type": "title",
        "value": "...",
        "variable": "..."
    },
    {
        "type": "message",
        "value": "...",
        "variable": "..."
    }
]

It seems that what you're trying to accomplish is to represent your java object in a way that you can send the object type and fields. 似乎您要完成的工作是以可以发送对象类型和字段的方式表示Java对象。 Under that assumption, I'd try to get away from manual serialization. 在这种假设下,我将尝试摆脱手动序列化。 Just create a DTO with the format that you need, that you can populate with the domain objects you have. 只需创建具有所需格式的DTO,即可使用您拥有的域对象填充该格式。 This would be an example: 这将是一个示例:

public class FooSerialization {

    public static class Foo {
        private String title;
        private String message;
    }

    public static class Foo2 {
        private String value;
        private String variable;
    }

    public static class ClassDTO {

        private String type;
        private List<FieldDTO> fields;

    }

    public static class FieldDTO {
        private String type;
        private String value;
        private String fieldName;
    }

    public static void main(String[] args) throws JsonProcessingException {

        Foo2 foo2 = new Foo2();
        foo2.setValue("valueMessage");
        foo2.setVariable("variableMessage");
        Foo foo = new Foo();
        foo.setMessage("messageMessage");
        foo.setTitle("titleMessage");

        ObjectMapper mapper = new ObjectMapper();

        List<ClassDTO> dtos = new ArrayList<ClassDTO>();
        dtos.add(convert(foo));
        dtos.add(convert(foo));
        System.out.println(mapper.writeValueAsString(dtos));
    }

    private static ClassDTO convert(Object obj) {
        ClassDTO dto = new ClassDTO();
        dto.setType(obj.getClass().getSimpleName());
        List<FieldDTO> fieldDTOs = new ArrayList<FieldDTO>();
        dto.setFields(fieldDTOs);

        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            FieldDTO fieldDto = new FieldDTO();
            try {
                fieldDto.setFieldName(field.getName());
                fieldDto.setValue(field.get(obj).toString());
                fieldDto.setType(field.getType().getSimpleName());
                fieldDTOs.add(fieldDto);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return dto;
    }

}

Getters and Setters are omitted for simplicity. 为了简单起见,省略了Getter和Setter。 This basically converts from Foo or Foo2 to certain ClassDTO, that contains type and a list of FieldDTOs that have the field details. 这基本上是从Foo或Foo2转换为某些ClassDTO,它包含类型和具有字段详细信息的FieldDTO列表。 Output looks like this: 输出看起来像这样:

[
    {
        "type": "Foo",
        "fields": [
            {
                "fieldName": "title",
                "type": "String",
                "value": "titleMessage"
            },
            {
                "fieldName": "message",
                "type": "String",
                "value": "messageMessage"
            }
        ]
    },
    {
        "type": "Foo2",
        "fields": [
            {
                "fieldName": "value",
                "type": "String",
                "value": "valueMessage"
            },
            {
                "fieldName": "variable",
                "type": "String",
                "value": "variableMessage"
            }
        ]
    }
]

It looks to me that you can solve lots of problems if you can use something like this: 在我看来,如果您可以使用以下方法,则可以解决很多问题:

@JsonFormat(shape=JsonFormat.Shape.ARRAY)
public static class Foo {
    @JsonProperty public Foo1 title;
    @JsonProperty public Foo2 message;
}

@JsonTypeInfo(use= JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
@JsonSubTypes({@JsonSubTypes.Type(value = Foo1.class, name = "title"),
               @JsonSubTypes.Type(value = Foo2.class, name = "message")})
public static class FooParent{
    @JsonProperty private String value;
    @JsonProperty private String variable;
}

public static class Foo1 extends FooParent{}
public static class Foo2 extends FooParent{}

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    Foo foo = new Foo();
    foo.title = new Foo1();
    foo.message = new Foo2();

    String serialized = mapper.writeValueAsString(foo);
    System.out.println(serialized);
}

Result is: 结果是:

[
    {"type":"title","value":null,"variable":null},      
    {"type":"message","value":null,"variable":null}
]

Read following blog json in java 在Java中阅读以下博客json

This post is a little bit old but still i want to answer you Question 这篇文章有点老了,但我仍然想回答你的问题

Step 1: Create a pojo class of your data. 第1步:创建数据的pojo类。

Step 2: now create a object using json. 步骤2:现在使用json创建一个对象。

Foo foo = null;
ObjectMapper mapper = new ObjectMapper();
try{
foo =  mapper.readValue(newFile("/home/sumit/foo.json"),Foo.class);
} catch (JsonGenerationException e){
e.printStackTrace();
}

For further reference you can refer following link 有关更多参考,您可以参考以下链接

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM