![](/img/trans.png)
[英]How can I get an element in an array based on value rather than index with Json.NET in C#?
[英]How can I get the value of the only field of a field in a json with json.net in a C# class
我想要這個 json:
{
"foo ": {
"bar": 5
}
}
要在此 class 中反序列化:
class MyClass
{
int foo;
}
像這樣:
void MyFunction(string _JSON)
{
string json = _JSON;
//json == {"foo ": {"bar": 5}}
MyClass c = JsonConvert.Deserialized<MyClass>(json);
//c.foo == 5
}
正如@DavidG 提到的,匹配 class 結構,您可以輕松獲得所需的值。 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:
根 myDeserializedClass = JsonConvert.DeserializeObject (myJsonResponse);
public class Foo
{
public int bar { get; set; }
}
public class Root
{
[JsonProperty("foo ")]
public Foo Foo { get; set; }
}
您可以通過JObject
從JSON
的特定字段中獲取值,如下所示:
void MyFunction(string _JSON)
{
JToken jobject = JObject.Parse(_JSON);
MyClass c = new MyClass()
{
foo = Convert.ToInt32(jobject["foo"]["bar"].ToString())
};
}
將其反序列化為匹配結構:
class MyJsonClass
{
public MyJsonFoo foo { get; set; }
}
class MyJsonFoo
{
public int bar { get; set; }
}
// and later...
var temp = JsonConvert.Deserialized<MyJsonClass>(json);
然后使用 object 創建您的 object:
var c = new MyClass { foo = temp.foo.bar };
本質上,您擁有的是與您的內部域( MyClass
)不匹配的外部依賴項(傳入的 JSON 結構)。 抽象服務(類、項目,無論它需要多么復雜)背后的依賴關系,它在內部反序列化結果並返回域 object。 這樣MyJsonClass
和MyJsonFoo
可以封裝在該服務中,而不會污染域。 該服務本質上只是兩個數據結構之間的轉換層。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.