Gson - 尝试将json字符串转换为自定义对象

Jos*_*osh 1 java json gson deserialization

这是我从服务器返回的Json

{"ErrorCode":1005,"Message":"Username does not exist"}
Run Code Online (Sandbox Code Playgroud)

这是我的错误类

public class ErrorModel {
public int ErrorCode;
public String Message;
}
Run Code Online (Sandbox Code Playgroud)

这是我的转换代码.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

它总是抛出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);
}
Run Code Online (Sandbox Code Playgroud)

基本逻辑是授权用户cretentials并将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;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用无效凭据调用上述身份验证时,将按预期返回错误结果.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;
}
Run Code Online (Sandbox Code Playgroud)

然后,我发送一个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);
}
Run Code Online (Sandbox Code Playgroud)

然后我将结果传递给我的解析器以查看它是否是错误

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,总是抛出JsonSyntaxException.

Mat*_*fer 6

可能有助于了解有关异常的更多信息,但相同的代码示例在这里工作正常.我怀疑你遗漏了一段导致问题的代码(可能是创建/检索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);
  }
}
Run Code Online (Sandbox Code Playgroud)