2013-12-21 34 views
0

我有一些代碼將寧靜的響應轉換爲遞歸結構。但是,我想要解析爲樹的內容被包裝到「treeprop」屬性中。有沒有更方便的方法來解析真實的內容?如何在使用jackson解析時防止冗餘字符串轉換步驟?

ObjectMapper mapper = new ObjectMapper(); 
JsonFactory jfac = new JsonFactory(); 
JsonParser jp = jfac.createParser(inputStream); 
JsonNode rootNode = mapper.readTree(jp); 

JsonNode path = rootNode.path("treeprop"); 
String realContent = mapper.writeValueAsString(path); 

MyTree mt = mapper.readValue(realContent, MyTree.class); 
inputStream.close(); 

請注意,解析本身在這裏不是問題。上面的代碼確實將inputStream正確地轉換爲一棵樹。然而,json經常大於1MB,所以暫時將它存儲在一個字符串中不能提高運行效率。

{ 
    "treeprop": { 
    "id": 0, 
    "children": [ 
     { 
     "id": 2, 
     "children": [ 
      { 
      "id": 3, 
      "children": [] 
      }, 
      { 
      "id": 4, 
      "children": [] 
      } 
     ] 
     }, 
     { 
     "id": 1, 
     "children": [] 
     } 
    ] 
    } 
} 

和類看起來大致是這樣的

class MyTree { 
    public Integer id; 
    public List<MyTree> children; 
} 

所以真正的問題是:有沒有一個更有效的替代TE實現相同的:

JsonNode path = rootNode.path("treeprop"); 
String realContent = mapper.writeValueAsString(path); 
MyTree mt = mapper.readValue(realContent, MyTree.class); 
+0

更多信息會對您有所幫助 - 首先,您要解析的json輸入示例;第二 - MyTree類。 – Eugen

+0

看看這個答案,我相信它會滿足你的需求。 - > http://stackoverflow.com/questions/20635220/json-parser-for-recursive-structure/20635380#20635380 –

回答

1
public class MyTreeWrapper { 
    private MyTree treeprop; 

    // getter, setter 
} 

... 

ObjectMapper mapper = new ObjectMapper(); 
MyTreeWrapper wrapper = mapper.readValue(inputStream, MyTreeWrapper.class); 
MyTree tree = wrapper.getTreeprop(); 

備選:

MyTree tree = mapper.reader(MyTree.class).readValue(rootNode.path("treeprop")); 
相關問題