0

我正在尝试使用 Jackson 库序列化 JSON 文档。下面是我手工创建的 JSON 文档。现在我需要使用 Jackson 序列化这个文档

示例-A

{
    "v" : {
        "site_id" : 0,
        "price_score" : 0.5,
        "confidence_score" : 0.2,
        "categories": {
            "123" : {
                "price_score": "0.5",
                "confidence_score": "0.2"
            },
            "321" : {
                "price_score": "0.2",
                "confidence_score": "0.4"
            }
        }
    }
}

到目前为止,我可以使用下面的代码并使用 Jackson- 制作 JSON 文档的这一部分

示例-B

{
  "v" : {
    "site_id" : 0,
    "price_score" : 0.5,
    "confidence_score" : 0.2
  }
}       

现在,我无法理解如何categories使用以下代码在我的 Example-B JSON 文档中添加(如 Example-A 中所示)部分的列表?

public static void main(String[] args) {

    Map<String, Object> props = new HashMap<String, Object>();
    props.put("site-id", 0);
    props.put("price-score", 0.5);
    props.put("confidence-score", 0.2);

    AttributeValue av = new AttributeValue();
    av.setProperties(props);

    /**
     * this will print out the JSON document like I shown in my Example-B
     * but I need to make it look like as in Example-A. I am not sure how
     * to achieve that?
     */
    System.out.println(av);

    // serialize it
    try {
        String jsonStr = JsonMapperFactory.get().writeValueAsString(attr);
        System.out.println(jsonStr);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

有人可以帮我吗?

4

1 回答 1

1

解决方案 1
在您的情况下,您可以使用

Map<String, Object> props = new HashMap<String, Object>();
props.put("site-id", 0);
props.put("price-score", 0.5);
props.put("confidence-score", 0.2);
Map<String, String> category123 = new HashMap<String, String>();
category123.put("price_score", "0.5");
category123.put("confidence_score", "0.2");
Map<String, String> category321 = new HashMap<String, String>();
category123.put("price_score", "0.2");
category123.put("confidence_score", "0.4");
Map<String, Object> categories = new HashMap<String, Object>();
categories.put("123", category123);
categories.put("321", category321);
props.put("categories", categories);  

解决方案 2:
或者您可以使用其他类来简化它,例如:

public class Category 
{
   private String price_score;
   private String confidence_score;

   public Category(String price_score, String confidence_score) 
   {
      this.price_score = price_score;
      this.confidence_score = confidence_score;
   }

   public Category() 
   {
   } 
   // getters/setters
}

主要方法

Map<String, Object> props = new HashMap<String, Object>();
props.put("site-id", 0);
props.put("price-score", 0.5);
props.put("confidence-score", 0.2);
Map<String, Category> categories = new HashMap<String, Category>();
categories.put("123", new Category("0.4", "0.2"));
categories.put("321", new Category("0.2", "0.5"));
props.put("categories", categories);
于 2013-09-14T22:19:26.790 回答