简体   繁体   中英

Convert JSON Request to C# object and send Response back in different JSON format

I am making a call to a webservice and getting following Json Request

{"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"]}}

I used https://json2csharp.com/ to convert my Json String to C# Classes

 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; }
    }

I need to send back a JSON Respond that is formatted that way

{"responseJson": {"session": {"id": "ABwppHF4mhTR8RAjnFSt7me_NFR1hRKHY5N6X0kfONIcz_VVPUOmR8VddWVJ3GM3G8ix3OR3O1Ew2wbldc5cRziYebVA","params": {},"languageCode": ""},"prompt": {"override": false,"firstSimple": {"speech": "Stellen Sie eine Frage","text": ""}}}}

https://json2csharp.com/ that results into this object structure

 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; } } }

My current code looks like this: I get an nullreferenceexception if i do it that way. I cant set any Values in the RespondJson object. I am new to programming. I would be very grateful for help

[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);
}

}

How would i do that? In short: I receive a request in JSON,but later on I need to send a response back in another JSON format.

The best way it is have two separate models. One pre request and second per response. Ofcourse you can reuse some classes anuse in Both models. In your json you can reuse the session object and then you have to create new class which will be represent prompt object. Example of your Response object:

  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; }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM