c# - 将 JSON 请求转换为 C# 对象并以不同的 JSON 格式发送回响应
问题描述
我正在调用网络服务并获得以下 Json 请求
{"handler":{"name":"abc"},"intent":{"name":"actions.intent.MAIN","params":{},"query":"Mit Google sprechen"},"scene":{"name":"actions.scene.START_CONVERSATION","slotFillingStatus":"UNSPECIFIED","slots":{},"next":{"name":"Start_Frage"}},"session":{"id":"ABwppHHVumDrliLJaLSikS6KnIlN7yYv6Z4XJCOYzEZt8Fr08RH6r0wtM2-E0v40lS2p1YosTDfpSCd5Lw","params":{},"typeOverrides":[],"languageCode":""},"user":{"locale":"de-DE","params":{},"accountLinkingStatus":"ACCOUNT_LINKING_STATUS_UNSPECIFIED","verificationStatus":"VERIFIED","packageEntitlements":[],"gaiamint":"","permissions":[],"lastSeenTime":"2021-04-01T10:06:59Z"},"home":{"params":{}},"device":{"capabilities":["SPEECH","RICH_RESPONSE","LONG_FORM_AUDIO"]}}
我使用https://json2csharp.com/将我的 Json 字符串转换为 C# 类
public class Handler
{
public string name { get; set; }
}
public class Params
{
}
public class Intent
{
public string name { get; set; }
public Params @params { get; set; }
public string query { get; set; }
}
public class Slots
{
}
public class Next
{
public string name { get; set; }
}
public class Scene
{
public string name { get; set; }
public string slotFillingStatus { get; set; }
public Slots slots { get; set; }
public Next next { get; set; }
}
public class Session
{
public string id { get; set; }
public Params @params { get; set; }
public List<object> typeOverrides { get; set; }
public string languageCode { get; set; }
}
public class User
{
public string locale { get; set; }
public Params @params { get; set; }
public string accountLinkingStatus { get; set; }
public string verificationStatus { get; set; }
public List<object> packageEntitlements { get; set; }
public string gaiamint { get; set; }
public List<object> permissions { get; set; }
public DateTime lastSeenTime { get; set; }
}
public class Home
{
public Params @params { get; set; }
}
public class Device
{
public List<string> capabilities { get; set; }
}
public class RequestJson
{
public Handler handler { get; set; }
public Intent intent { get; set; }
public Scene scene { get; set; }
public Session session { get; set; }
public User user { get; set; }
public Home home { get; set; }
public Device device { get; set; }
}
我需要发回以这种方式格式化的 JSON 响应
{"responseJson": {"session": {"id": "ABwppHF4mhTR8RAjnFSt7me_NFR1hRKHY5N6X0kfONIcz_VVPUOmR8VddWVJ3GM3G8ix3OR3O1Ew2wbldc5cRziYebVA","params": {},"languageCode": ""},"prompt": {"override": false,"firstSimple": {"speech": "Stellen Sie eine Frage","text": ""}}}}
https://json2csharp.com/导致这个对象结构
public class Params { } public class Session { public string id { get; set; } public Params @params { get; set; } public string languageCode { get; set; } } public class FirstSimple { public string speech { get; set; } public string text { get; set; } } public class Prompt { public bool @override { get; set; } public FirstSimple firstSimple { get; set; } } public class ResponseJson { public Session session { get; set; } public Prompt prompt { get; set; } } }
我当前的代码如下所示:如果我这样做,我会得到一个 nullreferenceexception。我无法在 RespondJson 对象中设置任何值。我是编程新手。我将非常感谢您的帮助
[HttpPost]
public async Task<IActionResult> PostWebHook([FromBody] RequestJson request)
{
ResponseJson response = new ResponseJson();
string body;
using (var reader = new StreamReader(Request.Body))
{
body = await reader.ReadToEndAsync();
// => doesnt work that way I get a nullreferenceexception
response.session.id = request.session.id; //nullreferenceexception
response.prompt.@override = false;
response.prompt.firstSimple.speech = "Test123";
//
}
return Ok(response);
}
}
我该怎么做?简而言之:我收到 JSON 格式的请求,但稍后我需要以另一种 JSON 格式发回响应。
解决方案
最好的方法是有两个独立的模型。一个预请求,每个响应第二个。当然,您可以在两个模型中重用一些类。在您的 json 中,您可以重用会话对象,然后您必须创建代表提示对象的新类。您的响应对象示例:
public class Params
{
}
public class Session
{
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("params")]
public Params Params { get; set; }
[JsonPropertyName("languageCode")]
public string LanguageCode { get; set; }
}
public class FirstSimple
{
[JsonPropertyName("speech")]
public string Speech { get; set; }
[JsonPropertyName("text")]
public string Text { get; set; }
}
public class Prompt
{
[JsonPropertyName("override")]
public bool Override { get; set; }
[JsonPropertyName("firstSimple")]
public FirstSimple FirstSimple { get; set; }
}
public class ResponseJson
{
[JsonPropertyName("session")]
public Session Session { get; set; }
[JsonPropertyName("prompt")]
public Prompt Prompt { get; set; }
}
public class Response
{
[JsonPropertyName("responseJson")]
public ResponseJson ResponseJson { get; set; }
}
推荐阅读
- google-cloud-platform - 为什么 GCSfuse 看不到 GS 存储桶,而 GSutil 可以?
- node.js - 错误:命令失败:gm convert pdf-image 转换
- sql - 在更新触发器中查找修改的字段
- json - REST 数据格式
- excel - 多张工作表的导入 Excel
- python - Python将数值数据转换回分类
- javascript - 用户名和密码未传递到同一页面
- postgresql - postgres 表中的最近点
- javascript - 如何在 Adobe Acrobat Reader 2017 中使用 Javascript 访问 3d pdf 中的对象?
- r - 如何从 data.frame 中删除指定的行