2

我正在学习我的第一个 Java Json 解析器库女巫是 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 的密钥名称:

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 ;
}
4

2 回答 2

3

您正在寻找的是以下方法fields()JsonNode

for (Iterator<Entry<String, JsonNode>> iterator = basketList.fields(); iterator.hasNext();) {
    Entry<String, JsonNode> item = iterator.next();   
    Integer idItem = Integer.parseInt(item.getKey());
    // snip
}
于 2013-05-14T15:13:47.250 回答
1

您可以将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

}
于 2013-05-13T08:55:06.837 回答