에 JSON 문자열을 변환하려고하면 여기 내 JSON 여기 오류 여기GSON는 - 사용자 정의 개체
public class ErrorModel {
public int ErrorCode;
public String Message;
}
내 변환 코드는 내 클래스 서버
{"ErrorCode":1005,"Message":"Username does not exist"}
에서 반환됩니다.
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을 던지고 있습니다. 어떤 아이디어가 내 문제가 될 수 있니?
편집 : 요청에 따라 여기에 더 자세히 설명되어 있습니다.
내 백엔드는 나머지 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을 정식 및 하나 또는 JSON JSON 같은 AuthenticationResult 같은 ExceptionModel를 반환한다. 예상대로
여기 내 서버 측 예외 모델 위의 인증이 잘못된 자격 증명 불려
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입니다.
안드로이드 쪽에서는 먼저 키 - 값 쌍을 가진 객체를 만듭니다.
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은 ASP.NET MVC 2 응용 프로그램에서 만들어지고 http 게시물을 통해 검색됩니다. – Josh
나는 여러분의 코드를 테스트 해 보았습니다. 여러분이 가진 것처럼 하드 코딩 된 json 문자열을 사용해도 JsonSyntaxException을 던졌습니다. 최신 Java (1.6) 및 최신 gson (1.6) – Josh
나에게 코드와 JSON이 올바르게 보이므로 문제를 어떻게 얻을 수 있는지 잘 모릅니다. 그러나 Gson과 함께 일할 수없는 경우 대체 방법을 고려해야합니다. – StaxMan