简体   繁体   English

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

[英]Gson - attempting to convert json string to custom object

Here is my Json returned from the server 这是我从服务器返回的Json

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

Here is my class for an error 这是我上课的错误

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

and here is my conversion code. 这是我的转换代码

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;
    }
}

It is always throwing a JsonSyntaxException. 它总是抛出JsonSyntaxException。 Any ideas what could be my problem here? 有什么想法可能是我的问题吗?

EDIT : As requested, here is further elaboration. 编辑 :根据要求,这是进一步的阐述。

My backend is an ASP.NET MVC 2 application acting as a rest API. 我的后端是一个充当Rest API的ASP.NET MVC 2应用程序。 The backend isn't the problem here, as my actions (and even server errors) all return Json (using the built in JsonResult ). 后端不是这里的问题,因为我的操作(甚至服务器错误)都返回Json(使用内置的JsonResult )。 Here's a sample. 这是一个样本。

[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);
}

The basic logic is to auth the user cretentials and either return an ExceptionModel as json or an AuthenticationResult as json. 基本逻辑是对用户凭据进行身份验证,然后将ExceptionModel作为json返回或将AuthenticationResult作为json返回。

Here is my server side Exception Model 这是我的服务器端异常模型

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;
    }
}

When the above authentication is called with invalid credentials, the error result is returned as expected. 当使用无效的凭据调用上述身份验证时,将按预期返回错误结果。 The Json returned is the Json above in the question. 返回的Json是上面问题中的Json。

On the android side, I first build an object with my key-value pairs. 在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;
}

Then, I send off an http post and return as a string whatever is sent back. 然后,我发送一个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);
}

Then I take that result and pass it into my parser to see if it is an error 然后,我得到那个结果并将其传递给解析器,以查看是否为错误

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;
    }
}

But, JsonSyntaxException is always thrown. 但是,始终会抛出JsonSyntaxException。

Might help to know more about the exception, but the same code sample works fine here. 可以帮助您更多地了解有关异常的信息,但是相同的代码示例在此可以正常工作。 I suspect there's a piece of code you omitted that's causing the problem (perhaps the creation/retrieval of the JSON string). 我怀疑您忽略了一段导致问题的代码(也许是JSON字符串的创建/检索)。 Here's a code sample that worked fine for me on Java 1.6 and Gson 1.6: 这是一个在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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM