使用java中的ObjectMapper进行Jackson序列化 [英] Jackson serialization with ObjectMapper in java
问题描述
我想使用对象映射器序列化不同类型的列表,但我不知道如何
一次将不同类型的列表对象传递给对象Mapper。以下是我的代码:
I want to serialize the different types of lists by using object mapper, but I do not know how to pass the different types of list objects into object Mapper at a time. The following is my code:
AccountingService accService = ServiceFactory.getAccountingService();
List<TaxCategory> taxCategoryList = accService.getAllTaxCategories();
ProductService productService = ServiceFactory.getProductService();
List<SimpleUom> simpleUomList = productService.getSimpleUomsList();
ObjectMapper objMapper;
objMapper.writeValueAsString(?)--
请你建议我要通过什么代替 ?在上面的代码中。这是因为我必须得到包含上面列表的jackson序列化字符串作为jsp中的单个字符串并解析该字符串以获得在客户端使用的单个列表。
Would You please suggest what I have to pass instead of ? in above code. This is because of i have to get the jackson serialized string that includes above lists as a single string in jsp and parse that string to get individual lists to be used at client side.
推荐答案
只需尝试:
ObjectMapper objMapper = new ObjectMapper();
String jsonString = objMapper.writeValueAsString(simpleUomList);
根据评论编辑:
您需要创建一个包装两个列表的类然后编写它:
You need to create a class wrapping your two lists and then write it:
public class MyLists {
private List<TaxCategory> taxCategoryList;
private List<SimpleUom> simpleUomList;
// + constructor, getters and setters
}
ObjectMapper objMapper = new ObjectMapper();
MyLists myLists = new MyLists(taxCategoryList, simpleUomList);
String jsonString = objMapper.writeValueAsString(myLists);
这篇关于使用java中的ObjectMapper进行Jackson序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!