1

I've a json data like the following which I'm getting from API. { "Location Code": "0000", "Main Image": "MainImage124", "Hero Image": "HeroImage2344", "City": "City1" }

I've a model class like following

`public class Class1 {
     public string LocationCode  { get; set; }
     public string MainImage { get; set; }
     public string HeroImage { get; set; }
     public string City { get; set; }
}`

I'm deserializing the api data using Newtonsoft.Json. But I'm missing the data for LocationCode, MainImage and HeroImage. I can see the data for City. I guess it's b'coz of the space in the property "Location Code" in json data.

How to remove the white spaces in Json Property (in this case the property name is "Location Code").
Please advise me on.

Or Is there any reason why the data is missing for LocationCode, MainImage and HeroImage after deserialization?

CSharpLearner
  • 43
  • 1
  • 7
  • 6
    Why not just specify the property names? `[JsonProperty("Location Code")]`, etc? See [this question](https://stackoverflow.com/questions/8796618/how-can-i-change-property-names-when-serializing-with-json-net/8796648). – ProgrammingLlama Jun 18 '21 at 16:24

2 Answers2

4

Annotate your property with the JSON names instead

using Newtonsoft.Json;

 public class Class1 
 {
     [JsonProperty("Location Code")]
     public string LocationCode { get; set; }
     [JsonProperty("Main Image")]
     public string MainImage { get; set; }
     [JsonProperty("Hero Image")]
     public string HeroImage { get; set; }
     public string City { get; set; }
 }

Ibram Reda
  • 1,882
  • 2
  • 7
  • 18
-1

String.Trim Method

You can use the String.Trim() in c# to remove the white spaces from your string.

YourProperty.Trim();

Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed.

In your case

LocationCode.Trim();
Safyan Yaqoob
  • 444
  • 3
  • 11