2012-11-30 203 views
0

如何獲取此字符串並將其放入String Array或HashMap?任何參考?將JSON字符串反序列化爲字符串數組

 { 
     "code" : 403, 
      "errors" : [ { 
       "domain" : "global", 
       "location" : "Authorization", 
       "locationType" : "header", 
       "message" : "The domain policy has disabled third-party Drive apps", 
       "reason" : "domainPolicy" 
      } ], 
     "message" : "The domain policy has disabled third-party Drive apps" 
    } 

====

這是我對傑克遜的解決方案:

public class TheErrorModel { 
    public int code; 
    public Collection<Error> errors; 
    public String message; 

    public TheErrorModel() { 
    } 

    public TheErrorModel(String json) 
      throws Exception { 
     ObjectMapper mapper = new ObjectMapper(); 
     TheErrorModelother = mapper.readValue(json, TheErrorModel.class); 

     this.code = other.code; 
     this.errors = other.errors; 
     this.message = other.message; 
    } 
} 

class Error { 
    public String domain; 
    public String location; 
    public String locationType; 
    public String message; 
    public String reason; 
} 

TheErrorModel theErrorModel = new TheErrorModel(json); 

所以我得到的東西像theErrorModel.message:d

+1

有很多libs在線提供。你有嘗試過嗎? –

+0

我有傑克遜,但我不知道使用它的想法是什麼:/ – lannyboy

+0

http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/ –

回答

2

您可以試試使用GSON http://code.google.com/p/google-gson/,使用非常簡單。你應該爲這個json模式創建類結構。

import com.google.gson.Gson; 
class YourErrorsJSON{ 
    private String domain 
    private String location; 
    private String locationType; 
    private String message; 
    private String reason 
} 

class YourJSON { 
    private int code; 
    private YourErrorsJSON[] errors; 
    private String message; 
} 
Gson gson = new Gson(); 
YourJSON obj = gson.fromJson(json, YourJSON.class); 
+0

順便說一句,那個消息只是一個錯誤,我不確定作者真的想要解析它。也許只是錯誤的子串就足夠了。 –

1

試試這個::

JSONObject yourObj = JSONObject.fromString(input_string); 
String code = yourObj.get("code"); // code will have a value 403 
+0

JSONObject的庫是什麼? org.json.JSONObject? – lannyboy

+0

如果我想使用傑克遜?我不包括你需要包括的很多庫 – lannyboy

+0

:: import net.sf.json.JSONArray; import net.sf.json.JSONObject; –