【发布时间】:2025-12-12 02:00:01
【问题描述】:
我将我的 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}"}
这是无效的,我不知道为什么。
Webservice 代码如下
[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}
【问题讨论】:
-
你在用“mn”对象做什么?这段代码仍然显示 Message = Json,它是一个字符串而不是 JsonObject。
-
mn 对象就在我单步执行代码的那一刻。它应该使用发布的值填充 Worksheets 类。
标签: java c# android json web-services