将JSON字符串反序列化为String Array

时间:2012-11-30 07:04:45

标签: java json

如何获取此字符串并放入String Array或HashMap?有没有参考?

     {
        "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);

所以我得到像ErrorModel.message:D

这样的东西

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

试试这个::

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