[英]Deserialize JSON property starting with @ symbol into C# dynamic object?
How to deserialize Json property to dynamic object if it starts with @ symbol. 如果以@符号开头,如何将Json属性反序列化为动态对象。
{
"@size": "13",
"text": "some text",
"Id": 483606
}
I can get id and text properties like this. 我可以像这样得到id和text属性。
dynamic json = JObject.Parse(txt);
string x = json.text;
Since you can't use @ in a C# token name, you would need to map the @size to something else, like "SizeString" (since it is a string in your JSON above). 由于您无法在C#标记名称中使用@,因此需要将@size映射到其他内容,例如“SizeString”(因为它是上面JSON中的字符串)。 I use the WCF data contract attribute, but you could use the equivalent JSON attribute
我使用WCF数据协定属性,但您可以使用等效的JSON属性
...
[DataMember(Name = "@size")]
public string SizeString { get; set; }
...
Here is an example of how to deserialize the Json string. 以下是如何反序列化Json字符串的示例。 Maybe you can adapt to your situation, or clarify your question.
也许你可以适应你的情况,或澄清你的问题。
...
string j = @"{
""@size"": ""13"",
""text"": ""some text"",
""Id"": 483606
}";
MyClass mc = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(j);
...
[DataContract]
public class MyClass
{
[DataMember(Name="@size")]
public string SizeString { get; set; }
[DataMember()]
public string text { get; set; }
[DataMember()]
public int Id { get; set; }
}
If you don't plan loading the Json into a predefined class, you can do the following... 如果您不打算将Json加载到预定义的类中,则可以执行以下操作...
var o = JObject.Parse(j);
var x = o["text"];
var size = o["@size"];
Assuming you use Json.NET: 假设你使用Json.NET:
public class MyObject
{
[JsonProperty("@size")]
public string size { get; set; }
public string text { get; set; }
public int Id { get; set; }
}
var result = JsonConvert.DeserializeObject<MyObject>(json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.