获取Rest Api不返回JSON字符串格式正确吗?

时间:2015-10-26 13:38:51

标签: java android json gson

我使用REST获取一个返回字符串的url资源,如下所示:

URL url = new URL(some_url_string);
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("GET");

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer response = new StringBuffer();

String inputLine;
while ((inputLine = reader.readLine()) != null) {
    response.append(inputLine);
}
reader.close();

String s = response.toString();

我尝试将其转换为我的班级:

MyClass temp = new Gson().fromJson(s, MyClass.class);

MyClass在哪里:

public class MyClass {
    @SerializedName("Number")
    public int number;

    @SerializedName("Date")
    public Long date;
}

问题是response.toString()正在返回:

"{\"Number\":2,\"Date\":1444953600}"

虽然,Gson希望字符串为:

{"Number":2,"Date":1444953600}

由于response.toString()在字符串的开头和结尾处返回上面的字符串并附加",因此我收到以下异常:

  

引起:java.lang.IllegalStateException:预期BEGIN_OBJECT但是第1行第2行STRING

     

在com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)

     

在com.google.gson.internal.bind.ReflectiveTypeAdapterFactory $ Adapter.read(ReflectiveTypeAdapterFactory.java:210)

这里的问题是GETresponse.toString()还是fromJson()

3 个答案:

答案 0 :(得分:0)

您必须在类和json中使用相同的属性名称。否则,您可以使用@SerializedName("...")指定其他名称

public class MyClass {
    @SerializedName("Number")
    public int number;

    @SerializedName("Date")
    public Long date;
}

答案 1 :(得分:0)

将这些步骤应用于您的回复字符串

 String s=  response.toString();
 s = s.trim();
 s = s.substring(1, s.length()-1);
 s = s.replace("\\", "");

s .replaceAll("\\\\", "");

答案 2 :(得分:0)

所以这不是问题......

  

只需创建一个带响应字符串的临时jsonobject

我已更新您的代码

URL url = new URL(some_url_string);
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("GET");

BufferedReader reader = new BufferedReader(new      InputStreamReader(connection.getInputStream()));
StringBuffer response = new StringBuffer();

String inputLine;
while ((inputLine = reader.readLine()) != null) {
   response.append(inputLine);
}
reader.close();

String s = response.toString();
JSONObject sObj=new JSONObject(s); 
// create this object and now pass this to serialize object using GSON
MyClass temp = new Gson().fromJson(sObj.toString(), MyClass.class);