我有一些使用Jackson属性创建json报告的课程
Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one","test1")
myMap.put("two","test2")
myMap.put("three","test3")
myMap.put("four","test4")
myMap.put("five","test5")
我从HashMap获取报告数据,其中还有其他键值对。
public class SearchResultsViewModel : BindableBase, IRegionMemberLifetime
{
// Stuff...
public bool KeepAlive => false;
}
我只需要地图中的第一个到第三个值,其他类中使用其他值。在输出中我想填写Instrument类的值。有干净利落的做法吗?
答案 0 :(得分:0)
您可以使用ObjectMapper.convert
方法将Instrument类的实例转换为哈希映射,如下所示:
public class JacksonConvert {
static class Instrument {
@JsonProperty("one")
private String myPropOne;
@JsonProperty("two")
private String myPropTwo;
@JsonProperty("three")
private String myPropThree;
Instrument(
final String myPropOne,
final String myPropTwo,
final String myPropThree) {
this.myPropOne = myPropOne;
this.myPropTwo = myPropTwo;
this.myPropThree = myPropThree;
}
}
public static void main(String[] args) {
final ObjectMapper objectMapper = new ObjectMapper();
final Instrument instrument = new Instrument("a", "b", "c");
final Map<String, String> report = objectMapper.convertValue(
instrument,
new TypeReference<Map<String, String>>() {});
System.out.println(report);
}
}
输出:
{one = a,two = b,three = c}