1

I have json with only one type which including some properties

{"Agreement":{"agreementId":"1","CreatedOn":"2016-09-02T09:25:05","ModifiedOn":"2019-06-30T23:30:00.173"}}

I`m using Newtonsoft JsonConvert.

Is it possible to parse it to model like this?

public class Agreement
{
public int Id {get; set;}
public DateTime CreatedOn {get; set;}
public DateTime ModifiedOn {get; set;}
}

Now i must declare additional class, which contains this type

public class AgreementAdditional
{
public Agreement Agreement {get; set;}
}

May be its duplicate, but i cant google it correctly

0

2 Answers 2

2

You could use the JObject class.

var json = File.ReadAllText("json1.json");
var example = JObject.Parse(json)["Agreement"].ToObject<Agreement>();

Although I see nothing wrong with the AgreementAdditional class as that's the exact format of your input.

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

Comments

2

You can use dynamic.

Using Newtonsoft you can do it like this:

dynamic result = JsonConvert.DeserializeObject(json);

And using JObject you can do it like this:

dynamic result = JObject.Parse(json);

To use the dynamic object, use it using the same names on the json file.

result.Agreement.agreementId
...

However, creating a class is still a better choice for code maintenance.

2 Comments

I think if OP goes this route then the statement would be agreement.Agreement...
dynamic type is not what i want. I will use two classes, thank you for advice!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.