Home > Back-end >  How to read a json key which has space in c#
How to read a json key which has space in c#

Time:06-20

This is the sample json

{
    "custom_data": {
        "Form Name": "Test OSP",
        "School": "Hamilton High School",
    }
}

I'm using .Net Core for front end without model classes.

I'm Able to get full json value in api call then stored in Jobject . problem comes when I try to access the specific key "Form Name" from the Json response

If I try to access the Form Name like this

dynamic FormName = reportResults.custom_data["Form Name"];

I'm getting error like this

((Newtonsoft.Json.Linq.JToken)Transactions.custom_data["Form Name"]).First' threw an exception of type
Error processing 'variables' request. Unknown Error: 0x89720013

'((Newtonsoft.Json.Linq.JToken)FormName).Last' threw an exception of type 'System.InvalidOperationException'

Is there is any other way to read it .. ? Thanks in advance

CodePudding user response:

There are no any problem with reading properties with whitespace in name:

using Newtonsoft.Json.Linq;
...
var reportResults = JObject.Parse(jsonFromQuestion);
var name = reportResults["custom_data"]["Form Name"].ToString(); // Test OSP

CodePudding user response:

you can use [JsonProperty] attribute for your classes

Data reportResults= JsonConvert.DeserializeObject<Data>(json);
var  formName = reportResults.custom_data.FormName;

classes

 public class CustomData
    {
        [JsonProperty("Form Name")]
        public string FormName { get; set; }
        public string School { get; set; }
    }

    public class Data
    {
        public CustomData custom_data { get; set; }
    }

  • Related