2011-02-17 90 views
0

這裏是我的Json從服務器GSON - 試圖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); 
} 

的基本邏輯是權威性用戶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; 
    } 
} 

當上述認證被稱爲無效的憑證,按預期的方式返回錯誤結果。 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總是拋出。

回答

4

可能有助於瞭解有關異常的更多信息,但相同的代碼示例在此處可以正常工作。我懷疑有一段你遺漏的代碼導致了這個問題(可能是創建/檢索JSON字符串)。下面是工作得很好,我對Java的1.6和1.6 GSON一個代碼示例:

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); 
    } 
} 
+0

的JSON是在ASP.NET MVC 2應用程序創建,並通過HTTP POST檢索。 – Josh 2011-02-18 14:04:58

相關問題