【问题标题】:Gson - attempting to convert json string to custom objectGson - 尝试将 json 字符串转换为自定义对象
【发布时间】:2011-02-17 22:19:45
【问题描述】:

这是我从服务器返回的 Json

{"ErrorCode":1005,"Message":"Username does not exist"}

这是我的错误课程

public class ErrorModel {
public int ErrorCode;
public String Message;
}

这是我的转换代码。

public static ErrorModel GetError(String json) {

    Gson gson = new Gson();

    try
    {
        ErrorModel err = gson.fromJson(json, ErrorModel.class);

        return err;
    }
    catch(JsonSyntaxException ex)
    {
        return null;
    }
}

它总是抛出一个 JsonSyntaxException。有什么想法可能是我的问题吗?

编辑:根据要求,这里是进一步的阐述。

我的后端是一个 ASP.NET MVC 2 应用程序,作为一个 REST API。后端不是这里的问题,因为我的操作(甚至服务器错误)都返回 Json(使用内置的 JsonResult)。这是一个示例。

[HttpPost]
public JsonResult Authenticate(AuthenticateRequest request)
{
    var authResult = mobileService.Authenticate(request.Username, request.Password, request.AdminPassword);

    switch (authResult.Result)
    {
         //logic omitted for clarity
         default:
            return ExceptionResult(ErrorCode.InvalidCredentials, "Invalid username/password");
            break;
    }

    var user = authResult.User;

    string token = SessionHelper.GenerateToken(user.UserId, user.Username);

    var result = new AuthenticateResult()
    {
        Token = token
    };

    return Json(result, JsonRequestBehavior.DenyGet);
}

基本逻辑是验证用户凭据并返回 ExceptionModel 作为 json 或 AuthenticationResult 作为 json。

这是我的服务器端异常模型

public class ExceptionModel
{
    public int ErrorCode { get; set; }
    public string Message { get; set; }

    public ExceptionModel() : this(null)
    {

    }

    public ExceptionModel(Exception exception)
    {
        ErrorCode = 500;
        Message = "An unknown error ocurred";

        if (exception != null)
        {
            if (exception is HttpException)
                ErrorCode = ((HttpException)exception).ErrorCode;

            Message = exception.Message;
        }
    }

    public ExceptionModel(int errorCode, string message)
    {
        ErrorCode = errorCode;
        Message = message;
    }
}

当使用无效凭据调用上述身份验证时,会按预期返回错误结果。返回的 Json 就是上面问题中的 Json。

在 android 端,我首先用我的键值对构建一个对象。

public static HashMap<String, String> GetAuthenticationModel(String username, String password, String adminPassword, String abbr)
{
    HashMap<String, String> request = new HashMap<String, String>();
    request.put("SiteAbbreviation", abbr);
    request.put("Username", username);
    request.put("Password", password);
    request.put("AdminPassword", adminPassword);

    return request;
}

然后,我发送一个 http 帖子,并将返回的任何内容作为字符串返回。

public static String Post(ServiceAction action, Map<String, String> values) throws IOException {
    String serviceUrl = GetServiceUrl(action);

    URL url = new URL(serviceUrl);

    URLConnection connection = url.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    String data = GetPairsAsString(values);

    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
    output.writeBytes(data);
    output.flush();
    output.close();

    DataInputStream input = new DataInputStream(connection.getInputStream());

    String line;
    String result = "";
    while (null != ((line = input.readLine())))
    {
        result += line;
    }
    input.close ();

    return result;
}

private static String GetServiceUrl(ServiceAction action)
{
    return "http://192.168.1.5:33333" + action.toString();
}

private static String GetPairsAsString(Map<String, String> values){

    String result = "";
    Iterator<Entry<String, String>> iter = values.entrySet().iterator();

    while(iter.hasNext()){
        Map.Entry<String, String> pairs = (Map.Entry<String, String>)iter.next();

        result += "&" + pairs.getKey() + "=" + pairs.getValue();
    }

    //remove the first &
    return result.substring(1);
}

然后我把这个结果传递给我的解析器,看看它是否是一个错误

public static ErrorModel GetError(String json) {

    Gson gson = new Gson();

    try
    {
        ErrorModel err = gson.fromJson(json, ErrorModel.class);

        return err;
    }
    catch(JsonSyntaxException ex)
    {
        return null;
    }
}

但是,总是抛出 JsonSyntaxException。

【问题讨论】:

    标签: java json gson deserialization


    【解决方案1】:

    可能有助于了解有关异常的更多信息,但相同的代码示例在这里可以正常工作。我怀疑您遗漏了一段导致问题的代码(可能是 JSON 字符串的创建/检索)。这是一个代码示例,在 Java 1.6 和 Gson 1.6 上运行良好:

    import com.google.gson.Gson;
    
    public class ErrorModel {
      public int ErrorCode;
      public String Message;
      public static void main(String[] args) {
        String json = "{\"ErrorCode\":1005,\"Message\":\"Username does not exist\"}";
        Gson gson = new Gson();
        ErrorModel err = gson.fromJson(json, ErrorModel.class);
        System.out.println(err.ErrorCode);
        System.out.println(err.Message);
      }
    }
    

    【讨论】:

    • Json 在 ASP.NET MVC 2 应用程序中创建并通过 http post 检索。
    • 我将您的代码作为测试并进行了尝试,即使您使用硬编码的 json 字符串,它也会抛出 JsonSyntaxException。我有最新的 java (1.6) 和最新的 gson (1.6)
    • 对我来说,代码和 JSON 看起来是正确的,所以我不知道你是怎么解决这个问题的。但是,如果您无法使用 Gson 解决问题,也许您应该考虑替代方案。
    猜你喜欢
    • 2015-01-11
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2017-01-24
    相关资源
    最近更新 更多