-1

I ran into a funny situation.

I am using the BlockCypher API to generate crypto addresses, and what BlockCypher returns as a response is a Json object with the following fields: "address", "public", and "private".

This is my code:

HttpClient client = new HttpClient(); 
HttpResponseMessage response = await client.GetAsync(endpoint);
if (response.IsSuccessStatusCode)
{
   string json = await response.Content.ReadAsStringAsync();
   dynamic dynamicJson = JsonConvert.DeserializeObject(json);
   return new MyAddress()
   {
     Address = (string)dynamicJson.address,
     PublicKey = (string)dynamicJson.public,
     PrivateKey = (string)dynamicJson.private
   };
}

but I am having problems since public and private are keywords in C# :)

Obviously, there are many alternatives, such as using dynamicJson["public"] or deserializing into an existing class to avoid dynamic, but I am just wondering if there is a way to escape these keywords or some other workaround.

Eutherpy
  • 4,471
  • 7
  • 40
  • 64
  • I dont think there is another way to escape – Mark Jan 10 '18 at 12:15
  • See: https://stackoverflow.com/questions/421257/how-do-i-use-a-c-sharp-keyword-as-a-property-name – Sebastian Hofmann Jan 10 '18 at 12:16
  • 1
    What a bad API... You should create your own class and use the `[JsonProperty("name")]` annotation – Camilo Terevinto Jan 10 '18 at 12:16
  • 4
    @CamiloTerevinto How is it the API's fault? You can't expect them to avoid every keyword in every language ever invented as json key. – CodesInChaos Jan 10 '18 at 12:23
  • 1
    @CodesInChaos There are many languages where `public` and `private` are keywords, the developer of the API should know that and use friendlier names – Camilo Terevinto Jan 10 '18 at 12:25
  • @CamiloTerevinto Sure, but there are many other keywords that may occur on a valid JSON where it´s not that obvious. Think of `asnyc` for example.or `lock`.Of course they exist in some languages, but you can´t expect developers of a library to be aware of *every* possible keyword that may exist in *any* language. – MakePeaceGreatAgain Jan 10 '18 at 12:58

1 Answers1

0

You could try like this;

public class JsonObject
{
    public string Address { get; set; }
    [JsonProperty("public")]
    public string PublicKey { get; set; }
    [JsonProperty("private")]
    public string PrivateKey { get; set; }
}

var jsonObject = JsonConvert.DeserializeObject<JsonObject>(json);
//jsonObject.PublicKey
lucky
  • 12,734
  • 4
  • 24
  • 46