How to use dynamic property names for a Json object

前端 未结 3 1111
悲&欢浪女
悲&欢浪女 2020-12-02 02:38

How can we make the JSON property name dynamic. For example

public class Value {
    @JsonProperty(value = \"value\")
    private String val;

    public vo         


        
3条回答
  •  我在风中等你
    2020-12-02 03:00

    You can use JsonAnySetter JsonAnyGetter annotations. Behind you can use Map instance. In case you have always one-key-object you can use Collections.singletonMap in other case use HashMap or other implementation. Below example shows how easy you can use this approach and create as many random key-s as you want:

    import com.fasterxml.jackson.annotation.JsonAnyGetter;
    import com.fasterxml.jackson.annotation.JsonAnySetter;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.util.Collections;
    import java.util.Map;
    import java.util.Objects;
    
    public class JsonApp {
    
        public static void main(String[] args) throws Exception {
            DynamicJsonsFactory factory = new DynamicJsonsFactory();
            ObjectMapper mapper = new ObjectMapper();
    
            System.out.println(mapper.writeValueAsString(factory.createUser("Vika")));
            System.out.println(mapper.writeValueAsString(factory.createPhone("123-456-78-9")));
            System.out.println(mapper.writeValueAsString(factory.any("val", "VAL!")));
        }
    }
    
    class Value {
    
        private Map values;
    
        @JsonAnySetter
        public void put(String key, String value) {
            values = Collections.singletonMap(key, value);
        }
    
        @JsonAnyGetter
        public Map getValues() {
            return values;
        }
    
        @Override
        public String toString() {
            return values.toString();
        }
    }
    
    class DynamicJsonsFactory {
    
        public Value createUser(String name) {
            return any("name", name);
        }
    
        public Value createPhone(String number) {
            return any("phone", number);
        }
    
        public Value any(String key, String value) {
            Value v = new Value();
            v.put(Objects.requireNonNull(key), Objects.requireNonNull(value));
    
            return v;
        }
    }
    

    Above code prints:

    {"name":"Vika"}
    {"phone":"123-456-78-9"}
    {"val":"VAL!"}
    

提交回复
热议问题