1

I have a string array that I want to deserialize. Essentially, it is just a list of objects. Note that the attributes have spaces in the names:

[    {        \"Event Name\": \"Hurricane Irma PR\",        \"Storm Start (LST)\": \"2017-08-30\",        \"Storm End (LST)\": \"2017-09-13\",        \"Grid Cell Number\": 16412,        \"Grid Cell State\": \"PR\",        \"Grid Cell Name\": \"Grid26_0\", ...

I created a public class to template the string based on specific attributes that I want ( I don't want all the data) but I am not sure how to handle for the spaces in the names of the attributes that I want.

    public class New_Events_Dataset
    {
        public string EventName { get; set; }
        public string StormStart { get; set; }
        public string StormEnd { get; set; }
        public string GridCellState { get; set; }
        public string GridCellName { get; set; }
        public string USGSGageSiteNo { get; set; }
        public string ReturnPeriodatGridCell { get; set; }
    }

When I apply the deserializer with my class New_Events_Dataset like this:

    var jsonResponse = returnJson.Deserialize<List<New_Events_Dataset>>(strresult);
    string json = new JavaScriptSerializer().Serialize(jsonResponse);
                return json;

I end up returning something like this. What am I doing wrong?

[{"EventName":null,"StormStart":null,"StormEnd":null,"GridCellState":null,"GridCellName":null,"USGSGageSiteNo":null,"ReturnPeriodatGridCell":null}
2

1 Answer 1

4

Unfortunately keys must match exactly each other.
One of the best ways to solve your problem is to define JsonProperty attribute for each property to get Deserialized object correctly. You can specify property's json key name with it.
You can take a look to this question and it's answer for better understanding: An example of JsonProperty

Edit:
As in comments mentioned, because you are using JavaScriptSerializer JsonPropertyAttribute doesn't work in this situation. But you can use it by adding Newtonsoft.Json Nuget Package and using it's deserilizer this way:

JsonConvert.DeserializeObject<AzureResourceData>(jsonString);
Sign up to request clarification or add additional context in comments.

2 Comments

JsonPropertyAttribute is used by the json.net serializer, but OP is using JavaScriptSerializer. JsonPropertyAttribute will not work in this situation.
Yep. It worked once I added "JsonConvert.DeserializeObject<List<New_Events_Dataset>>(strresult);" and [JsonProperty("<Exact Name")] to my class variables. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.