0

I'm looking for a way to map multiple properties to different "sections" of a JSon string using newtonsoft.

What I currently have is the following (doesn't work at all, but maybe you'll get a better idea of what I'm trying to accomplish):

public class example
{
  [JsonProperty("this.is.an.example")]
  public string ex { get; set; }

  [JsonProperty("this.is.another")]
  public string ex2;
}

While the corresponding JSon string might be structured like so:

{
  "this" :
  {
    "is" : {
      "an" : {
        "example" : "this is the first value I want to return"
      }
      "another" : "this is the second value"
    }
  }
}

I want it this way so that I can easily deserialize several of these JSon strings like so:

example y = JsonConvert.DeserializeObject<example>(x);
//where x is the JSon string shown above and
//y.ex == "this is the first value I want to return"
//y.ex2 == "this is the second value
//Also note that example is the class name of the resulting object

Hopefully you can see what I'm trying to accomplish. Thanks in advance for any help, any input is appreciated!

Note:

After a bit of searching I found a similar question that didn't receive an answer. But maybe it'll help JSON.NET deserialize/serialize JsonProperty JsonObject

Community
  • 1
  • 1

1 Answers1

2

You can simply use dynamic keyword, instead of writing some complex code for custom deserialization.

string json = @"{""this"":{""is"":{""an"":{""example"":""this is the first value I want to return""}}}}";
dynamic jObj = JObject.Parse(json);
string example = jObj.@this.@is.an.example;

PS: Since this and is are reserved-words in c# I used @ in front of them .

L.B
  • 114,136
  • 19
  • 178
  • 224
  • I thought about this.. I'd prefer to have an object that I could just deserialize to, though. – user3645275 Jun 18 '14 at 11:11
  • I say this because the json that I'm dealing with can be hundreds of thousands of lines long (an object I don't feel like creating every time I want to deserialize) – user3645275 Jun 18 '14 at 11:33
  • Just realized that was my bad (I had been working on two similar deserialization codes and mixed them up a bit) I edited the question to reflect what my actual issue is. Sorry about that! – user3645275 Jun 18 '14 at 12:00