我试图从下面的JSON对象获取FIRST属性(params)并将其作为C#中的结构存储。我在this页面上使用了该解决方案。但我没有成功。如果有人可以帮助或指出我正确的方向,那将是非常有帮助的。谢谢。
{
"params" : [
{"OneInstance" : "true"},
{"Single" : "3"},
{"File_Name" : "test.exe"},
{"Conf_Name" : "inst.bin"}
],
"directories" : [
{"file1": "C:/Program Files (x86)/whatever/example"},
{"file2": "C:/Program Files/another/example"}
]}
public static JValuesStruct paramValues;
StreamReader streamReader = new StreamReader(@"Sample.json");
using (JsonTextReader reader = new JsonTextReader(streamReader))
{
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartObject)
{
// Load each object from the stream and do something with it
JObject obj = JObject.Load(reader);
JsonSerializer serializer = new JsonSerializer();
paramValues = (JValuesStruct)serializer.Deserialize(new JTokenReader(obj), typeof(JValuesStruct));
}
}
}
public struct JValuesStruct
{
public bool OneInstance { get; set; }
public string Single { get; set; }
public string File_Name { get; set; }
public string Conf_Name { get; set; }
}
答案 0 :(得分:0)
你走了。它完美无缺。首先从Nuget下载“newtonsoft.json”并将其添加到您的项目中。 struct myStruct
是转换为struct的反序列化json对象。
public void DeserializeMyJsonObject()
{
string json;
using (StreamReader r = new StreamReader("d:\\json.txt"))
{
json = r.ReadToEnd();
}
var myStruct = JsonConvert.DeserializeObject<YourStruct>(json);
}
public struct YourStruct
{
[JsonProperty("params")]
public List<Object> KeyAndProperties { get; set; }
}