Jackson将字段名写入嵌套树

时间:2016-12-14 13:35:36

标签: java jackson

我有以下用例:

我必须将“标题”:“G103 MMath数学(4年)”写成一个Json字符串,它构成了一个更大的Json树的一部分:

       {
        "dimensions": [
          "www.southampton.ac.uk/maths/undergraduate/courses/g100_mathematics.page",
          "\"People Also Viewed\""
        ],
        "metrics": [
          {
            "values": [
              "1275"
            ]
          }
        ]
      },

Json必须变成这样:

      {
        "dimensions": [
          "www.southampton.ac.uk/maths/undergraduate/courses/g103_mmath.page",
          "\"People Also Viewed\""
        ],
        "title": "G103 MMath Mathematics (4 years)",
        "metrics": [
          {
            "values": [
              "105"
            ]
          }
        ]
      }

我现在正在使用Java 6(将在不久的将来成为Java 8)。我已经回顾了Gson和Jackson,并了解到还有Boon。我试图在Gson中这样做,并且无法弄清楚如何在不创建Pojos的情况下读取Json String(使用http://www.jsonschema2pojo.org/)。所以我决定使用Jackson 2.5.1。我得到了一点,我可以在那里创建一个Json漂亮的TokenBuffer,我可以将从Json String读取的树写入一个新文件。

以下是方法:

    /**
     * Generates Json from original Google Analytics report to include extra data on each page.
     * @param json input Json String
     * @return output returns the converted Json
     * @throws IOException when the File cannot be read
     */
     public String generateJson(String json) throws IOException {
       String output;
       //Create a JsonGenerator
       ObjectMapper mapper = new ObjectMapper();
       JsonParser parser = mapper.getFactory().createParser(json);
       TokenBuffer buffer = parser.readValueAs(TokenBuffer.class);

       JsonGenerator gen = mapper
                            .getFactory()
                            .createGenerator(new   File("/Users/arnout/dev/southampton/sitepublisher.git/soton-test/workarea/resultJson.json"), JsonEncoding.UTF8);

       gen
            .useDefaultPrettyPrinter()
            .writeObject(buffer);

       // read json in buffer back as tree
       JsonNode root = mapper.readTree(buffer.asParser());
       JsonNode dimensions = null;
       log.debug("GoogleAnalyticsGenerator --- generateJson -- Jackson generated json in TokenBuffer is " + root );
       int count = root.get("reports").get(0).get("data").get("rows").size();
       for ( int i = 0; i < count ; i++ ){
        dimensions = root.get("reports").get(0).get("data").get("rows").get(i).get("dimensions");
       log.debug("GoogleAnalyticsGenerator --- generateJson -- Jackson root dimension array is " + dimensions );
    }

       gen.close();
       parser.close();

       //Close the JsonGenerator

      output = json.toString();
      return output;
      }
    }

目前,当我在此方法上运行单元测试时,我返回了Json缓冲区,我可以返回JsonNode维度(来自Google Analytics的结果)。

 5165 [main] DEBUG u.a.s.l.g.a.GoogleAnalyticsGenerator -   GoogleAnalyticsGenerator --- generateJson -- Jackson generated json in  TokenBuffer is {"reports":[{"columnHeader":{"dimensions": ["ga:pagePath","ga:segment"],"metricHeader":{"metricHeaderEntries":[{"name":"pageviews","type":"INTEGER"}]}},"data":{"maximums":[{"values":["1356"]}],"minimums":[{"values":["2"]}],"rowCount":150,"rows":[{"dimensions":["www.southampton.ac.uk/maths/undergraduate/courses/g100_mathematics.page","\"People Also Viewed\""],"metrics":[{"values":["1356"]}]},{"dimensions":["www.southampton.ac.uk/maths/undergraduate/courses/g103_mmath.page","\"People Also Viewed\""],"metrics":[{"values":["105"]}]},{"dimensions":["www.southampton.ac.uk/maths/undergraduate/courses/g120_mathematical_studies.page","\"People Also Viewed\""],"metrics":[{"values":["103"]}]},{"dimensions":["www.southampton.ac.uk/maths/undergraduate/courses/g1nh_maths_with_finance.page","\"People Also Viewed\""],"metrics":[{"values":["73"]}]},{"dimensions":["www.southampton.ac.uk/maths/undergraduate/courses/g1n3_maths_with_actuarial_science.page","\"People Also Viewed\""],"metrics":[{"values":["69"]}]},{"dimensions":["www.southampton.ac.uk/maths/undergraduate/courses/g1g3_maths_with_statistics.page","\"People Also Viewed\""],"metrics":[{"values":["50"]}]}],"samplesReadCounts":["488083"],"samplingSpaceSizes":["867358"],"totals":[{"values":["2557"]}]},"nextPageToken":"6"}]} 
 5165 [main] DEBUG u.a.s.l.g.a.GoogleAnalyticsGenerator -   GoogleAnalyticsGenerator --- generateJson -- Jackson root dimension array  is  ["www.southampton.ac.uk/maths/undergraduate/courses/g100_mathematics.page","\"People Also Viewed\""] 
 5165 [main] DEBUG u.a.s.l.g.a.GoogleAnalyticsGenerator - GoogleAnalyticsGenerator --- generateJson -- Jackson root dimension array is ["www.southampton.ac.uk/maths/undergraduate/courses/g103_mmath.page","\"People Also Viewed\""] 
 5165 [main] DEBUG u.a.s.l.g.a.GoogleAnalyticsGenerator - GoogleAnalyticsGenerator --- generateJson -- Jackson root dimension array is ["www.southampton.ac.uk/maths/undergraduate/courses/g120_mathematical_studies.page","\"People Also Viewed\""] 
 5165 [main] DEBUG u.a.s.l.g.a.GoogleAnalyticsGenerator - GoogleAnalyticsGenerator --- generateJson -- Jackson root dimension array is ["www.southampton.ac.uk/maths/undergraduate/courses/g1nh_maths_with_finance.page","\"People Also Viewed\""] 
 5166 [main] DEBUG u.a.s.l.g.a.GoogleAnalyticsGenerator - GoogleAnalyticsGenerator --- generateJson -- Jackson root dimension array is ["www.southampton.ac.uk/maths/undergraduate/courses/g1n3_maths_with_actuarial_science.page","\"People Also Viewed\""] 
 5166 [main] DEBUG u.a.s.l.g.a.GoogleAnalyticsGenerator - GoogleAnalyticsGenerator --- generateJson -- Jackson root dimension array is ["www.southampton.ac.uk/maths/undergraduate/courses/g1g3_maths_with_statistics.page","\"People Also Viewed\""] 

我的问题是如何添加标题?

如果更快/更容易(或任何其他平台),我很乐意使用Gson或Boon。

1 个答案:

答案 0 :(得分:0)

我在Jackson 2上实现了序列化,因为我测试了Json元素&#34;行&#34;毕竟实际上永远不会改变。以下是我参考的内容:

 /**
 * Generates Json from original Google Analytics report to include extra data on each page.
 * @return output returns the converted Json
 * @throws IOException when the File cannot be read
 */
public void generateJson(File input) throws IOException {

    try {
        //Convert object to JSON string and pretty print.
        ObjectMapper mapper = new ObjectMapper();

        //read the retrieved Json values into the Object members.
        GoogleAnalyticsJsonObject gao = mapper.readValue(input, GoogleAnalyticsJsonObject.class);
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(gao);
        JsonParser parser = mapper.getFactory().createParser(json);
        TokenBuffer buffer = parser.readValueAs(TokenBuffer.class);

        //Regenerate the Json file.
        JsonGenerator gen = mapper.getFactory().createGenerator(
                new File(String.valueOf(input)), JsonEncoding.UTF8);
        gen.useDefaultPrettyPrinter().writeObject(buffer);

        //Close the JsonGenerator.
        gen.close();
        parser.close();
    } catch (JsonGenerationException jge) {
        log.error("JsonGenerationException " + jge);
    }
}

我创建了一个序列化的包,并放入了我从jsonschema2pojo生成的所有Pojos,并添加了一个名为Title的新Object。我像这样添加了对象:

@JsonInclude(JsonInclude.Include.ALWAYS)

@JsonPropertyOrder({     &#34;尺寸&#34 ;,     &#34;标题&#34 ;,     &#34;度量&#34; }) 公共类Row {

@JsonProperty("dimensions")
private List<String> dimensions = null;
@JsonProperty("title")
private String title = null;
@JsonProperty("metrics")
private List<Metric> metrics = null;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

// Set a Sl4J logger
private final Logger log = LoggerFactory.getLogger(Row.class);

/**
 * 
 * @return
 *     The title
 */
@JsonProperty("title")
public String getTitle() {
    String result = "";
    //generate the title from the Page
    //page title for this item
    //get the associated content
    //read out the content fields for : Code, Name, Award, Duration with some conditional logic
    List<String> dimensions = getDimensions();
    String pageTitle = "";
    Title title = new Title();
    for ( String dim : dimensions ) {
        if ( dim.startsWith("www")) {  //filter out the views from the dimensions, leaving us with page URLs
            try {
                result = title.getTitle(dim);
            } catch (FileManagerException e) {
                e.printStackTrace();
            }
        }
    }

    return result;
}

/**
 * 
 * @param title
 *     The title
 */
@JsonProperty("title")
public void setTitle(String title) {
    this.title = title;
}

/**
 *
 * @return
 *     The dimensions
 */
@JsonProperty("dimensions")
public List<String> getDimensions() {
    return dimensions;
}

/**
 *
 * @param dimensions
 *     The dimensions
 */
@JsonProperty("dimensions")
public void setDimensions(List<String> dimensions) {
    this.dimensions = dimensions;
}

/**
 * 
 * @return
 *     The metrics
 */
@JsonProperty("metrics")
public List<Metric> getMetrics() {
    return metrics;
}

/**
 * 
 * @param metrics
 *     The metrics
 */
@JsonProperty("metrics")
public void setMetrics(List<Metric> metrics) {
    this.metrics = metrics;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
    return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
    this.additionalProperties.put(name, value);
}

}