将哈希表转换为 JSON,并在筛选一些键时。

huangapple go评论91阅读模式
英文:

Convert hashmap to json while filtering some keys?

问题

我试图将哈希映射转换为 JSON,同时过滤一些键。我已经尝试了 Jackson,但结果始终包含所有键。

Map<String, String> hashtable = new HashMap<>();
hashtable.put("KEY1", "VALUE1");
hashtable.put("KEY2", "VALUE2");
hashtable.put("KEY3", "VALUE3");

ObjectMapper objectMapper = new ObjectMapper();
FilterProvider filter = new SimpleFilterProvider().addFilter("filter", SimpleBeanPropertyFilter.filterOutAllExcept("KEY1"));
objectMapper.setFilterProvider(filter);
System.err.println(objectMapper.writeValueAsString(hashtable));

我的键是动态的,有没有更有效的方法来做到这一点?

Jackson 过滤的方法对我来说很完美,因为我需要为同一个 HashMap 生成多个具有不同过滤器的 JSON。是否可能使用 Jackson 来实现这一点?

英文:

I am trying to convert hashmap to json while filtering some keys. I have tried with Jackson but the result always have all the keys in it.

Map&lt;String, String&gt; hashtable = new HashMap();
hashtable.put(&quot;KEY1&quot;, &quot;VALUE1&quot;);
hashtable.put(&quot;KEY2&quot;, &quot;VALUE2&quot;);
hashtable.put(&quot;KEY3&quot;, &quot;VALUE3&quot;);

ObjectMapper objectMapper = new ObjectMapper();
FilterProvider filter = new SimpleFilterProvider().addFilter(&quot;filter&quot;, SimpleBeanPropertyFilter.filterOutAllExcept(&quot;KEY1&quot;));
objectMapper.setFilterProvider(filter);
System.err.println(objectMapper.writeValueAsString(hashtable));

My keys are dynamic, Is there more efficent way to do this?

Jackson method of filtering is perfect to me, since i need to generate multiple json's with different filter for the same HashMap. Is is possible to make this work with Jackson?

答案1

得分: 1

你可以设置一个包括一个 SimpleBeanPropertyFilterFilterProvider

注意: 在这个示例中,validKeys 可以作为参数传递给 createFilterProvider 并存储在 FilterProvider 上,而不是在 KeyFilter 驱动程序上。

英文:

You can set up a FilterProvider that includes a SimpleBeanPropertyFilter.

Note: In this example, the validKeys could be passed as an argument to createFilterProvider and stored on the FilterProvider, rather than on the KeyFilter driver.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

public class KeyFilter {
    private static ObjectMapper mapper;
    private static Set&lt;String&gt; validKeys;

    static {
        mapper = new ObjectMapper();
        mapper.setFilterProvider(createFilterProvider());

        validKeys = new HashSet&lt;&gt;();
        validKeys.add(&quot;KEY1&quot;);
    }

    public static void main(String[] args) throws JsonProcessingException {
        Map&lt;String, String&gt; hashtable = new HashMap&lt;&gt;();

        hashtable.put(&quot;KEY1&quot;, &quot;VALUE1&quot;);
        hashtable.put(&quot;KEY2&quot;, &quot;VALUE2&quot;);
        hashtable.put(&quot;KEY3&quot;, &quot;VALUE3&quot;);

        System.out.println(mapper.writeValueAsString(hashtable)); // {&quot;KEY1&quot;:&quot;VALUE1&quot;}
    }

    // Derived from: https://stackoverflow.com/a/25232485/1762224
    private static FilterProvider createFilterProvider() {
        SimpleFilterProvider filterProvider = new SimpleFilterProvider();
        final String filterName = &quot;valid-key-filter&quot;;
        mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
            @Override
            public Object findFilterId(Annotated a) {
                if (Map.class.isAssignableFrom(a.getRawType())) {
                    return filterName;
                }
                return super.findFilterId(a);
            }
        });
        filterProvider.addFilter(filterName, new SimpleBeanPropertyFilter() {
            @Override
            protected boolean include(BeanPropertyWriter writer) {
                return true;
            }
            @Override
            protected boolean include(PropertyWriter writer) {
                return validKeys.contains(writer.getName());
            }
        });
        return filterProvider;
    }
}

答案2

得分: 1

Here is the translated content:

这里 是您问题的答案。您应该创建一个没有任何字段的 mixinSource 类并将其添加到 objectMapper。然后,您可以动态过滤您的映射。

@JsonFilter("filter")
public class DynamicMixIn {

}
Map<String, String> hashtable = new HashMap();
hashtable.put("KEY1", "VALUE1");
hashtable.put("KEY2", "VALUE2");
hashtable.put("KEY3", "VALUE3");

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addMixIn(Object.class, DynamicMixIn.class);
FilterProvider filter = new SimpleFilterProvider().addFilter("filter", SimpleBeanPropertyFilter.serializeAllExcept("KEY1"));
objectMapper.setFilterProvider(filter);
String filtered = objectMapper.writeValueAsString(hashtable); // {"KEY2":"VALUE2","KEY3":"VALUE3"}
英文:

Here is the answer of your question. You should create mixinSource Class without any fields and add it to the objectMapper. Then you can filter out your map dynamically

@JsonFilter(&quot;filter&quot;)
public class DynamicMixIn {

}
Map&lt;String, String&gt; hashtable = new HashMap();
hashtable.put(&quot;KEY1&quot;, &quot;VALUE1&quot;);
hashtable.put(&quot;KEY2&quot;, &quot;VALUE2&quot;);
hashtable.put(&quot;KEY3&quot;, &quot;VALUE3&quot;);

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addMixIn(Object.class, DynamicMixIn.class);
FilterProvider filter = new SimpleFilterProvider().addFilter(&quot;filter&quot;, SimpleBeanPropertyFilter.serializeAllExcept(&quot;KEY1&quot;));
objectMapper.setFilterProvider(filter);
String filtered = objectMapper.writeValueAsString(hashtable); // {&quot;KEY2&quot;:&quot;VALUE2&quot;,&quot;KEY3&quot;:&quot;VALUE3&quot;}

huangapple
  • 本文由 发表于 2023年8月4日 23:52:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定