2012-12-28 43 views
2

我有一個JSON字符串POJO:映射JSON回用JSON和傑克遜庫

{ 
    "fruit": { 
     "weight":"29.01", 
     "texture":null 
    }, 
    "status":"ok" 
} 

...那我試圖映射回一個POJO:

public class Widget { 
    private double weight; // same as the weight item above 
    private String texture; // same as the texture item above 

    // Getters and setters for both properties 
} 

上面的字符串(我試圖映射)實際上包含在org.json.JSONObject中,可以通過調用該對象的toString()方法獲得。

我想用Jackson JSON對象/ JSON映射框架做這種映射,到目前爲止,這是我最好的嘗試:當傑克遜readValue(...)方法被執行

try { 
    // Contains the above string 
    JSONObject jsonObj = getJSONObject(); 

    ObjectMapper mapper = new ObjectMapper(); 
    Widget w = mapper.readValue(jsonObj.toString(), Widget.class); 

    System.out.println("w.weight = " + w.getWeight()); 
} catch(Throwable throwable) { 
    System.out.println(throwable.getMessage()); 
} 

遺憾的是這段代碼拋出一個異常:

Unrecognized field "fruit" (class org.me.myapp.Widget), not marked as ignorable (2 known properties: , "weight", "texture"]) 
    at [Source: [email protected]; line: 1, column: 14] (through reference chain: org.me.myapp.Widget["fruit"]) 

我需要的映射器:

  1. 忽略外部大括號(「{‘和’}」)共
  2. 更改fruitWidget
  3. 忽略status

如果做到這一點的唯一方法是調用JSONObjecttoString()方法,那就這樣吧。但是我想知道Jackson是否帶有已經與Java JSON庫一起工作的「開箱即用」的東西?

無論哪種方式,寫傑克遜映射是我的主要問題。任何人都可以發現我要去哪裏嗎?提前致謝。

+1

你似乎在想你...你不要的對象。你的JSON表示(並且將映射到)帶有「水果」字段(保存包含兩個其他字段的對象)和「狀態」字段的對象。 –

+0

所以沒有辦法配置映射器忽略/別名字段?這在使用Castor和XStream的XML-land中是可行的。我想我只是假設*在JSON/Jackson-land中也是如此。畢竟,[不是**映射**應該實現的內容](http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch)?有多少數據庫表格完美映射回POJO?如果像Hibernate這樣的庫不允許進行配置,它們就沒有多大用處。 – IAmYourFaja

+0

但是......它確實映射。你試圖映射到與JSON對象不同的東西。相關是這個:http://stackoverflow.com/a/13873443/302916這是我的答案有人試圖做同樣的事情,但與Gson。我並沒有在Jackson中使用自定義的序列化/反序列化,但我確信有一種方法可以做到這一點。最簡單的解決方案就是創建一個內部類,就像那個答案中的最後一個例子。 –

回答

4

你需要有一類PojoClass包含(具有-A)Widget實例調用fruit

試試這個在您的映射:

String str = "{\"fruit\": {\"weight\":\"29.01\", \"texture\":null}, \"status\":\"ok\"}"; 
    JSONObject jsonObj = JSONObject.fromObject(str); 
    try 
    { 
     // Contains the above string 

     ObjectMapper mapper = new ObjectMapper(); 
     PojoClass p = mapper.readValue(jsonObj.toString(), new TypeReference<PojoClass>() 
     { 
     }); 

     System.out.println("w.weight = " + p.getFruit().getWeight()); 
    } 
    catch (Throwable throwable) 
    { 
     System.out.println(throwable.getMessage()); 
    } 

這是你Widget類。

public class Widget 
{ private double weight; 
    private String texture; 
    //getter and setters. 
} 

這是你PojoClass

public class PojoClass 
{ 
    private Widget fruit; 
    private String status; 
    //getter and setters. 
} 
+0

這行是什麼'JSONObject jsonObj = JSONObject.fromObject(str);'實際上做了什麼? –

+1

如果'jackson'庫已經擁有了將java對象從/到JSON轉換所需的全部功能,爲什麼我必須使用'org.json'中的'JSONObject'和'jackson'中的'ObjectMapper'? https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/ –

+0

@MagnoC - 隨意編輯答案。答案本身已超過4年。 – Srinivas