[英]How to convert json array of K/V to Java HashMap with Jackson JSON
我正在学习我的第一个Java Json解析器librairie女巫是Jackson JSON。
我正在尝试将ID / NOTE列表作为Java对象转换为HashMap列表。
我的Json输入看起来像这样
var basketList = [
{
"name": "Basket 1",
"productList": {
//Id Item to incremente for ordering
"14":{
// quantity to be add to this Id
"quantity":6,
"note": "Thing"
},
"15":{
"quantity":4,
"note": "Another Thing"
},
}
},
{
"name": "Basket 2",
"productList": {
"14":{
"quantity": 16,
"note": "Thing"
},
"15":{
"quantity":2,
"note": "Another Thing"
},
"17":{
"quantity":7,
"note": "Some Thing"
}
}
}
]
我的产品列表是动态的,因此我不想为此创建Java对象,
我的第一个想法是在Java中建立一个新的productList,并将每个数量添加到正确的产品ID中。
我在网上找不到任何有关如何执行此操作的示例,我正在尝试使用ObjectMapper()。readTree()并与JsonNode一起玩
我无法使其正常运作,我们将不胜感激
我已经做到了,但是我仍然坚持如何获取我最后一个JsonNode的Key名称:
String JSON = myJavaItem.getJson();
JsonNode JavaItem = mapper.readTree( JSON );
List<Product> listIwantCreate = BuildATestOrderList( JavaItem );
public static List<Product> BuildATestOrderList( JsonNode node )
{
List<Product> productList = new ArrayList<Product>();
JsonNode cabinetList = node.path( "cabinet" );
if ( !cabinetList.isMissingNode() )
{
for ( JsonNode cabinet : cabinetList )
{
JsonNode basketList= cabinet.path( "basketList" );
if ( !basketList.isMissingNode() )
{
for ( JsonNode item : productList )
{
// I need to populate here
Integer idItem; // how to get the key of current item ?
Integer qtity = item.path( "quantity" ).getIntValue();
Product p = new Product();
p.setIdItem( idItem );
p.setQuantity(qtity);
productList.add( p );
}
}
}
}
return productList ;
}
您正在寻找的是JsonNode
的方法fields()
:
for (Iterator<Entry<String, JsonNode>> iterator = basketList.fields(); iterator.hasNext();) {
Entry<String, JsonNode> item = iterator.next();
Integer idItem = Integer.parseInt(item.getKey());
// snip
}
您可以将杰克逊映射器的 TypeFactory
与类似这样的代码一起使用。
objectMapper.readValue(yourJsonString, TypeFactory.mapType(Map.class, String.class, TypeFactory.collectionType(List.class, Product.class));
假设您的Product
看起来像这样。
class Product {
int quantity;
String note;
//getter - setter
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.