[英]C#: How to trim a json string and put values into correct class
我有一个 JSON 字符串,我想将其剪切并将值放入正确的类中。 我如何在 C# 中做到这一点?
{
\"First\":{\"FirstBool\":1, \"aString\":\"hello\"},
\"Second\":{\"AnotherBool\":0,\"aString\":\"Hi again\"},
\"Third\":{\"ThirdBool\":0,\"aString\":\"Hi for the 3rd time\", \"AdditionalString\":\"ADDITIONAL STRING\"}
}
这就是我设置类以获取 JSON 值的方式。
public class First{
public static bool FirstBool {get; set;}
public static string aString {get; set;}
}
public class Second{
public static bool AnotherBool {get; set;}
public static string aString {get; set;}
}
public class Third{
public static bool ThirdBool {get; set;}
public static string aString {get; set;}
public static string AdditionalString {get; set;}
}
首先你的班级看起来像
public class First {
public int FirstBool { get; set; }
public string aString { get; set; }
}
public class Second {
public int AnotherBool { get; set; }
public string aString { get; set; }
}
public class Third {
public int ThirdBool { get; set; }
public string aString { get; set; }
public string AdditionalString { get; set; }
}
public class Result {
public First First { get; set; }
public Second Second { get; set; }
public Third Third { get; set; }
}
然后你可以使用 JavaScriptSerializer 反序列化你的 json
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Result objResult = (Result)json_serializer.DeserializeObject("<your JSON>");
你的 JSON 字符串First
无效,它就像"aString":"hello""
应该是"aString":"hello"
所以我希望并假设它是一个错字
您可以安装Newtonsoft JSON然后创建类
public class First
{
[JsonProperty("FirstBool")]
public int FirstBool { get; set; }
[JsonProperty("aString")]
public string aString { get; set; }
}
public class Second
{
[JsonProperty("AnotherBool")]
public int AnotherBool { get; set; }
[JsonProperty("aString")]
public string aString { get; set; }
}
public class Third
{
[JsonProperty("ThirdBool")]
public int ThirdBool { get; set; }
[JsonProperty("aString")]
public string aString { get; set; }
[JsonProperty("AdditionalString")]
public string AdditionalString { get; set; }
}
public class ClsResult
{
[JsonProperty("First")]
public First First { get; set; }
[JsonProperty("Second")]
public Second Second { get; set; }
[JsonProperty("Third")]
public Third Third { get; set; }
}
并像这样反序列化它
string jsonstr = File.ReadAllText(YourJSONFile);
var ser = JsonConvert.DeserializeObject<ClsResult>(jsonstr);
如果您使用的是 Visual Studio,您可以使用 Edit-> Paste Special -> Paste JSON as classes 找出任何 json 所需的类结构。
创建一个可以反序列化以满足您的要求的根类。
public class Rootobject
{
public First First { get; set; }
public Second Second { get; set; }
public Third Third { get; set; }
}
public class First
{
public int FirstBool { get; set; }
public string aString { get; set; }
}
public class Second
{
public int AnotherBool { get; set; }
public string aString { get; set; }
}
public class Third
{
public int ThirdBool { get; set; }
public string aString { get; set; }
public string AdditionalString { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.