简体   繁体   中英

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#. 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. Struct myStruct is your deserialized json object converted to a struct.

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM