3

I'm calling third party api from my asp.net mvc project. That api requires json object that has property name with space. But in c# we can't create property name with space. How Can I do that, I'm stuck?

I have tried using JsonProperty, but It is not working. I have tried to replace string in serialize string and then send that string to api but that gives me total error.

{
 "Single":14000,
 "Double":14500,
 "Triple":15000,
 "ExtraBed":15500,
 "ExtraChild":16000,
 "ExtraAdult":16000
}

But instead of ExtraBed, I have to pass as 'Extra Bed'.

Basil Kosovan
  • 888
  • 1
  • 7
  • 30
dev_la
  • 31
  • 3
  • Have you tryed [JsonProperty(PropertyName = "Extra Bed")]? – Basil Kosovan Jun 26 '19 at 11:27
  • I'd use [Newtonsoft](https://www.newtonsoft.com/json) for a clean and uncomplicated solution – Dominick Jun 26 '19 at 11:30
  • What do you use for serialization?. Could you please provide more code? Looks like serialization ignore your attribute.Show how you make serialization – Basil Kosovan Jun 26 '19 at 11:33
  • @BasilKosovan : yes I have tried that also – dev_la Jun 26 '19 at 11:33
  • [JsonProperty(PropertyName = "Extra Bed")] public decimal ExtraBed { get; set; }var p = new JavaScriptSerializer().Serialize(_AxisRoom); AxisRoom _hotelnew = JsonConvert.DeserializeObject(p); – dev_la Jun 26 '19 at 11:35
  • @ScottyDoesKnow : I use but in get api, like in response property name is changed but this is about post api request – dev_la Jun 26 '19 at 11:39
  • 1
    @dev_la , GET, POST doesn't matter . This is just about serialising/deserialsing – Dominick Jun 26 '19 at 11:58
  • `JavaScriptSerializer` doesn't support renaming of properties, see [JavaScriptSerializer - custom property name](https://stackoverflow.com/a/32488106/3744182). – dbc Jun 26 '19 at 21:08

1 Answers1

4

JsonPropertyAttribute doesn't impact on JavaScriptSerializer. There is no attribute for JavaScriptSerializer in order to change property name.You can write a custom JavaScriptConverter for it, but I recomend just use Newtonsoft.

 class AxisRoom
 {
     [JsonProperty("Extra Bed")]
     public decimal ExtraBed { get; set; }
 }


 AxisRoom _AxisRoom = new AxisRoom { ExtraBed = 3 };
 var result = JsonConvert.SerializeObject(_AxisRoom);

result is equal to {"Extra Bed":3.0}

Basil Kosovan
  • 888
  • 1
  • 7
  • 30