[英]Json Http Post Android
我将JSON数据发布到我的C#服务堆栈Web服务中。
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("CustomerLine1", worksheet.getCustomerLine1());
jsonObject.accumulate("CustomerLine2", worksheet.getCustomerLine2());
jsonObject.accumulate("CustomerLine3", worksheet.getCustomerLine3());
jsonObject.accumulate("Status", worksheet.getStatus());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
Log.d("dasd", json);
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
我从Log.d(“ dasd”,json);得到的响应; 是
{"CustomerLine1":"gh","CustomerLine2":"dg","CustomerLine3":"eg","Status":0}
这是有效的json。 但是我从网络服务获得的响应是
{"responseStatus":{"message":"{CustomerLine1:gh,CustomerLine2:dg,CustomerLine3:eg,Status:0}"}
这是无效的,我也不知道为什么。
Web服务摘要如下
[EnableCors(allowedMethods: "POST")]
public class WorksheetService : Service
{
public object Any(String Json)
{
var rs = new ResponseStatus()
{
Message = Json
};
return new WorksheetsResponse { ResponseStatus = rs };
}
}
谢谢
**更新**
我正在将Json字符串从我的android应用传递到我的API并对其进行反序列化。
public object Any(String Json)
{
var mn = JsonSerializer.DeserializeFromString<Worksheets>(Json);
var rs = new ResponseStatus()
{
Message = Json
};
return new WorksheetsResponse { ResponseStatus = rs };
}
但是没有从Worksheets类中填充CustomerLine1,CustomerLine2和CustomerLine3。
看来,当来自应用程序的帖子到达API时,其被接收为
{CustomerLine1:gh,CustomerLine2:dg,CustomerLine3:eg,Status:0}
并不是
{"CustomerLine1":"gh","CustomerLine2":"dg","CustomerLine3":"eg","Status":0}
return语句告诉服务以这种方式返回json。 如果您希望嵌套对象返回JSON而不是字符串,则可以执行以下操作:
public class WorksheetService : Service
{
public object Any(JsonObject Json)
{
var rs = new ResponseStatus()
{
Message = Json
};
return new WorksheetsResponse { ResponseStatus = rs };
}
}
如果只想记录原始的json字符串,则不要将其包装在ResponseStatus对象中返回。
public class WorksheetService : Service
{
public object Any(JsonObject Json)
{
return Json;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.