2016-12-14 44 views
0

我有以下的使用情況:傑克遜寫字段名的嵌套樹

我必須寫「稱號」:「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和傑克遜,瞭解到也有Boon。我試圖在Gson中做到這一點,並不知道如何在不創建Pojos的情況下閱讀Json字符串(使用http://www.jsonschema2pojo.org/)。所以我決定使用Jackson 2.5.1。我明白了,我可以創建一個帶有Json的TokenBuffer,並且可以將從Json字符串讀取的樹寫入一個新文件。

這裏是方法:

/** 
    * 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尺寸背部(與谷歌分析的結果)。

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

你爲什麼不想要POJO?在這裏,沒有它,事情就會像你的代碼一樣快速搞亂。這只是做了很多胡說,並返回它傳遞給它的參數! – glee8e

+0

我有一個問題,我如何在我們的Web應用程序中使用Pojos而無需手動生成它們,因爲Google Analytics的JSon頻繁更改爲其他內容。 Google Analytics(分析)的Json更改後,如何避免不必手動生成Pojos? –

+0

這不是我所期望的。試試這個:http://stackoverflow.com/q/4110664得到一個JSONObject,然後創建一個新的JsonPrimitive並調用jsonObject.add(「title」,jsonPrimitive) – glee8e

回答

0

我已經在Jackson 2上實現了序列化,因爲我測試了Json元素「rows」實際上從來不會改變。下面是我得到的工作以供參考:

/** 
* 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); 
    } 
} 

我創建了一個包序列化,並把所有的POJO我從jsonschema2pojo產生的,我添加了一個名爲標題給它新的對象。我添加這樣的對象:

@JsonInclude(JsonInclude.Include.ALWAYS) 

@JsonPropertyOrder({ 「尺寸」, 「標題」, 「度量」 }) 公共類行{

@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); 
} 

}