I would like this json :
{
"foo ": {
"bar": 5
}
}
To be deserialized in this class :
class MyClass
{
int foo;
}
Like this :
void MyFunction(string _JSON)
{
string json = _JSON;
//json == {"foo ": {"bar": 5}}
MyClass c = JsonConvert.Deserialized<MyClass>(json);
//c.foo == 5
}
CodePudding user response:
As @DavidG mentioned, match the class structure and you can easily get the value you want. You could go to the point of using this site to help you: https://json2csharp.com The site will give you the c# class structure of:
Root myDeserializedClass = JsonConvert.DeserializeObject (myJsonResponse);
public class Foo
{
public int bar { get; set; }
}
public class Root
{
[JsonProperty("foo ")]
public Foo Foo { get; set; }
}
CodePudding user response:
Deserialize it into a matching structure:
class MyJsonClass
{
public MyJsonFoo foo { get; set; }
}
class MyJsonFoo
{
public int bar { get; set; }
}
// and later...
var temp = JsonConvert.Deserialized<MyJsonClass>(json);
And then use that object to create your object:
var c = new MyClass { foo = temp.foo.bar };
Essentially what you have is an external dependency (an incoming JSON structure) which doesn't match your internal domain (MyClass
). Abstract that dependency behind a service (class, project, however complex it needs to be) which internally deserializes the result and returns the domain object. That way MyJsonClass
and MyJsonFoo
can be encapsulated within that service and not pollute the domain. The service is essentially just a translation layer between the two data structures.
CodePudding user response:
You can get value from a specific field from JSON
by JObject
like this:
void MyFunction(string _JSON)
{
JToken jobject = JObject.Parse(_JSON);
MyClass c = new MyClass()
{
foo = Convert.ToInt32(jobject["foo"]["bar"].ToString())
};
}