簡體   English   中英

Gson-嘗試將json字符串轉換為自定義對象

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

這是我從服務器返回的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。 有什么想法可能是我的問題嗎?

編輯 :根據要求,這是進一步的闡述。

我的后端是一個充當Rest API的ASP.NET MVC 2應用程序。 后端不是這里的問題,因為我的操作(甚至服務器錯誤)都返回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。

可以幫助您更多地了解有關異常的信息,但是相同的代碼示例在此可以正常工作。 我懷疑您忽略了一段導致問題的代碼(也許是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);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM