Store Hardcoded JSON string to variable

后端 未结 4 964
情书的邮戳
情书的邮戳 2021-02-05 01:48

I\'m having an issue storing this json string to a variable. It\'s gotta be something stupid I am missing here

private string someJson = @\"{
    \"ErrorMessage         


        
4条回答
  •  遇见更好的自我
    2021-02-05 02:27

    Writing JSON inline with c# in strings is a bit clunky because of the double quotes required by the JSON standard which need escaping in c# as shown in the other answers. One elegant workaround is to use c# dynamic and JObject from JSON.Net.

    dynamic message = new JObject();
    message.ErrorMessage = "";
    message.ErrorDetails = new JObject();
    message.ErrorDetails.ErrorId = 111;
    message.ErrorDetails.Description = new JObject();
    message.ErrorDetails.Description.Short = 0;
    
    Console.WriteLine(message.ToString());
    
    // Ouputs:
    // { 
    //   "ErrorMessage": "",
    //   "ErrorDetails": {
    //     "ErrorID": 111,
    //     "Description": {
    //       "Short": 0
    // .....  
    

    See https://www.newtonsoft.com/json/help/html/CreateJsonDynamic.htm.

提交回复
热议问题