Richard
Richard

Reputation: 6116

Jackson Serialize without field name

This is slight extension of my previous question. So based on dambros' answer, the json now looks like:

"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 (i.e remove "title" :).

Upvotes: 0

Views: 11419

Answers (4)

sumit kumar
sumit kumar

Reputation: 632

Read following blog json in java

This post is a little bit old but still i want to answer you Question

Step 1: Create a pojo class of your data.

Step 2: now create a object using 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

Upvotes: -2

zafrost
zafrost

Reputation: 576

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}
]

Upvotes: 1

Ulises
Ulises

Reputation: 9625

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. 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. 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. This basically converts from Foo or Foo2 to certain ClassDTO, that contains type and a list of FieldDTOs that have the field details. 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"
            }
        ]
    }
]

Upvotes: 1

Andreas
Andreas

Reputation: 159086

That is not valid JSON, however this is:

{
    "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.

You should read the JSON spec.


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:

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

Upvotes: 3

Related Questions