2012-05-21 146 views
-2

我寫了以下內容:傑克遜JSON異常

ObjectMapper oMapper = new ObjectMapper(); 
Object oPOJO = null; 

String p_strJSON = "{\"name\" : { \"first\" : \"Joe\", \"last\" : " 
    + "\"Sixpack\" },\"gender\" : \"MALE\",\"verified\" : \"false\"," 
    + "\"userImage\" : \"Rm9vYmFyIQ==\"}"; 

try 
{ 
    oPOJO = oMapper.readValue(p_strJSON, User.class); 
} 
catch(Throwable oThrowable) 
{ 
    System.out.println(oThrowable.getMessage()); 

    throw new RuntimeException(oThrowable); 
} 

而且,當執行正在以下異常消息:

無法反序列化java.lang.String中的實例進行START_OBJECT的token [at:Source:[email protected];行:1,列:1]

我是否正確使用Jackson?我正在使用1.9.6 JAR - 我需要在claspath中設置任何東西嗎?

+0

你是什麼p_clsType類? – Joey

+0

對不起 - 現在的例子很好走 – IAmYourFaja

+0

是你的名字對象在用戶定義爲字符串和「名稱」對象 – Joey

回答

2

鑑於你的用戶類看起來是這樣的,你的代碼通過

public class User { 
    private Name name; 
    private String gender; 
    private boolean verified; 
    private String userImage; 

    // getter and setter 
} 

public class Name { 
    private String first; 
    private String last; 

    // getter and setter 
} 
+0

謝謝@Joey!出於好奇,爲什麼'name'必須是'Name'實例?我把它當作一個String ... – IAmYourFaja

+0

因爲當傑克遜看到一個「{」它是一個對象的開始。嘗試將JSON可視化爲例如http://jsonformatter.curiousconcept.com/或http://jsonviewer.stack.hu/ – Joey