簡體   English   中英

Jackson JSON 序列化無字段名

[英]Jackson JSON Serialization without field name

我有一個 JAVA POJO,它有很多領域。 其中一個字段是Map<String, Object>我使用Custom JsonSerializer因為它可以有多種類型的Objects 我只想知道如何避免僅針對此Map<String,Object>字段的fieldname名序列化。 對於 POJO 中的所有其他字段,我想擁有字段名稱,但僅出於此目的,我想將其刪除。

截至目前,當使用Jackson searlizer 時,我得到以下 output:

{
  "isA" : "Human",
  "name" : "Batman",
  "age" : "2008",
  "others" : {
    "key1" : "value1",
    "key2" : {
      "key3" : "value3"
    },
    "key5" : {
      "key4" : "One",
      "key4" : "Two"
    }
  }
}

我想獲得以下 output :(我要做的就是刪除Map<String,Object>字段名稱,但保留其子項。)

{
  "isA" : "Human",
  "name" : "Batman",
  "age" : "2008",
  "key1" : "value1",
  "key2" : {
    "key3" : "value3"
  },
  "key5" : {
    "key4" : "One",
    "key4" : "Two"
  }
}

以下是ObjectMapper使用的Human.class POJO:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, visible = true, property = "isA")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
@NoArgsConstructor
@ToString
class Human {
    private String isA;
    private String name;
    private String age;

    @JsonSerialize(using = MyCustomSearlize.class)
    private Map<String, Object> others = new HashMap<>();
}

以下是 MAP 在 Searlization 過程中使用的Custom searlizer Searlizer:

class MyCustomSearlize extends JsonSerializer<Map<String, Object>> {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void serialize(Map<String, Object> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        recusiveSerializer(value, gen, serializers);
        gen.writeEndObject();
    }

    public void recusiveSerializer(Map<String, Object> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        for (Map.Entry<String, Object> extension : value.entrySet()) {
            if (extension.getValue() instanceof Map) {
                //If instance is MAP then call the recursive method
                gen.writeFieldName(extension.getKey());
                gen.writeStartObject();
                recusiveSerializer((Map) extension.getValue(), gen, serializers);
                gen.writeEndObject();
            } else if (extension.getValue() instanceof String) {
                //If instance is String directly add it to the JSON
                gen.writeStringField(extension.getKey(), (String) extension.getValue());
            } else if (extension.getValue() instanceof ArrayList) {
                //If instance if ArrayList then loop over it and add it to the JSON after calling recursive method
                for (Object dupItems : (ArrayList<Object>) extension.getValue()) {
                    if (dupItems instanceof Map) {
                        gen.writeFieldName(extension.getKey());
                        gen.writeStartObject();
                        recusiveSerializer((Map) dupItems, gen, serializers);
                        gen.writeEndObject();
                    } else {
                        gen.writeStringField(extension.getKey(), (String) dupItems);
                    }
                }
            }
        }
    }
}


以下是我的Main class:

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

        Human person = new Human();

        person.setName("Batman");
        person.setAge("2008");
        Map<String, Object> others = new HashMap<>();
        others.put("key1", "value1");
        Map<String, Object> complex = new HashMap<>();
        complex.put("key3", "value3");
        others.put("key2", complex);
        Map<String, Object> complex2 = new HashMap<>();
        List<String> dup = new ArrayList<>();
        dup.add("One");
        dup.add("Two");
        complex2.put("key4", dup);
        others.put("key5", complex2);
        person.setOthers(others);

        final ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule simpleModule = new SimpleModule();
        objectMapper.registerModule(simpleModule);
        final String jsonEvent = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(person);
        System.out.println(jsonEvent);
    }
}

以下是我嘗試過的事情:

  1. 我試圖在@JsonValue Map會刪除我所有的其他值(姓名、年齡、isA 等)
  2. 我嘗試了@JsonAnyGetter ,它適用於MapString ,但不適用於ArrayList 作為我要求的一部分,我在我的應用程序中以不同方式處理ArrayList位。

有沒有辦法讓它與@JsonSerialize@JsonAnyGetter一起使用,因為我無法同時使用它們。

有人可以幫忙解決這個問題嗎? 請指導我找到適當的文檔或解決方法,非常感謝。

wiki 頁面聽起來@JsonUnwrapped注釋應該做你想做的事。

@JsonUnwrapped:與 POJO 結構相比,用於定義該值的屬性注釋在序列化時應“解包”(並在反序列化時再次包裝),從而導致數據結構扁平化。

class 的Javadoc也有一個看起來合適的示例。

正如另一個答案中提到的@JsonUnwrapped可能有效,但我使用以下方法使其工作。 在這里發布,因為它可能對將來的某人有所幫助:

我在 Map 的Getter方法上添加了@JsonAnyGetter@JsonSearlizeMap工作。

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, visible = true, property = "isA")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
@NoArgsConstructor
@ToString
class Human {
    private String isA;
    private String name;
    private String age;

    @JsonIgnore
    private Map<String, Object> others = new HashMap<>();

    @JsonAnyGetter
    @JsonSerialize(using = MyCustomSearlize.class)
    public Map<String,Object> getOther(){
        return others;
    }
}

MyCustomSearlize class 代碼中,我刪除了開始和結束 object

    @Override
    public void serialize(Map<String, Object> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        recusiveSerializer(value, gen, serializers);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM