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

1 Answer 1

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.@[email protected];

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

Sign up to request clarification or add additional context in comments.

3 Comments

I thought about this.. I'd prefer to have an object that I could just deserialize to, though.
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)
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!

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.