【发布时间】:2013-05-11 01:07:16
【问题描述】:
我的 Android 应用程序向我的 .NET Web Api 发出 HttpPost 请求。
我正在使用 json 数据类型和 gson 类来序列化我的对象。
这是我关于序列化的代码:
HttpPost post = new HttpPost();
post.setURI(new URI("my url goes here"));
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", username);
hashMap.put("userCredentials", new Gson().toJson(credentials, UCredentials.class));
// username and credentials are parameters.
post.setHeader("Content-Type", "application/json; charset=utf-8");
post.setEntity(new StringEntity(new Gson().toJson(hashMap)));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(post);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// If successful.
}
除了hashMap.put("userCredentials", new Gson().toJson(credentials, UCredentials.class)); 代码行,一切正常。但是有了这条线......
Gson 类给我的 json 为:
{
"userCredentials":
"{
\"emailOrUsername\":\"asd@sadas.com\",
\"password\":\"113\"
}",
"username":"sdggfsdgf"
}
它不是有效的 json 模式。我需要像这样的 json 输出:
{
"userCredentials":
{
"emailOrUsername":"asd@sadas.com",
"password":"113"
},
"username":"sdggfsdgf"
}
我应该怎么做才能做到这一点?
提前致谢。
【问题讨论】: