[英]Retrieve(deserialize) a specific property from a json object to a C# struct (json deserialization)
I am attempting to get ONLY the FIRST property (params) from the JSON object below and store it as a struct in C#. 我试图仅从下面的JSON对象获取FIRST属性(参数),并将其存储为C#中的结构。 I was using the solution on this page.
我正在使用此页面上的解决方案。 But I was not successful.
但是我没有成功。 If anyone could help or point me in the right direction it would be very helpful.
如果有人可以帮助或指出正确的方向,那将非常有帮助。 Thank you.
谢谢。
{
"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; }
}
Here you go. 干得好。 It works perfect.
完美的作品。 First download "newtonsoft.json" from Nuget and add it to your project.
首先从Nuget下载“ newtonsoft.json”并将其添加到您的项目中。 Struct
myStruct
is your deserialized json object converted to a struct. Struct
myStruct
是将反序列化的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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.