使用Jackson序列化JSON文档

时间:2013-09-14 21:32:18

标签: java json serialization jackson jsonserializer

我正在尝试使用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
  }
}       

现在,我无法理解如何使用下面的代码在我的Example-B JSON文档中添加categories的列表(如示例-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();
    }

}

有人可以帮我吗?

1 个答案:

答案 0 :(得分: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);