C# Json.Net Deserialize Json with different "key" parameter

newtonsoft json deserialize
json dynamic property name c#
change json property name c#
deserialize json to object c#
get json property name c#
newtonsoft json serialize
deserialize multiple json objects c#
json.net deserialize array of different objects

I am trying to deserialize JSON using the Json.NET library. JSON which I receive looks like:

{
    "responseHeader": {
        "zkConnected": true,
        "status": 0,
        "QTime": 2
    },
    "suggest": {
        "mySuggester": {
            "Ext": {
                "numFound": 10,
                "suggestions": [
                    {
                        "term": "Extra Community",
                        "weight": 127,
                        "payload": ""
                    },
                    {
                        "term": "External Video block",
                        "weight": 40,
                        "payload": ""
                    },
                    {
                        "term": "Migrate Extra",
                        "weight": 9,
                        "payload": ""
                    }
                ]
            }
        }
    }
}

The problem is that the "Ext" that you can see in it is part of the parameter passed in the query string and will always be different. I want to get only the values assigned to the term "term".

I tried something like this, but unfortunately does not works:

public class AutocompleteResultsInfo
{
    public AutocompleteResultsInfo()
    {
        this.Suggest = new Suggest();
    }
    [JsonProperty("suggest")]
    public Suggest Suggest { get; set; }
}

public class Suggest
{
    [JsonProperty("mySuggester")]
    public MySuggesterElement MySuggesterElement { get; set; }
}

public struct MySuggesterElement
{
    public MySuggester MySuggester;
    public string JsonString;

    public static implicit operator MySuggesterElement(MySuggester MySuggester) =>new MySuggesterElement { MySuggester = MySuggester };
    public static implicit operator MySuggesterElement(string String) => new MySuggesterElement { JsonString = String };
}

public class MySuggester
{
    [JsonProperty("suggestions")]
    public Suggestions[] Suggestions { get; set; }
}

public class Suggestions
{
    [JsonProperty("term")]
    public string Autocopmplete { get; set; }
}

internal class SuggesterElementConverter : JsonConverter
{
    public override bool CanConvert(Type t)
    {
        return t == typeof(MySuggesterElement) || t == typeof(MySuggesterElement?);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        switch (reader.TokenType)
        {
            case JsonToken.String:
            case JsonToken.Date:
                var stringValue = serializer.Deserialize<string>(reader);
                return new MySuggesterElement { JsonString = stringValue };
            case JsonToken.StartObject:
                var objectValue = serializer.Deserialize<MySuggester>(reader);
                return new MySuggesterElement { MySuggester = objectValue };
        }
        throw new Exception("Cannot unmarshal type MySuggesterElement");
    }

    public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
    {
        var value = (MySuggesterElement)untypedValue;
        if (value.JsonString != null)
        {
            serializer.Serialize(writer, value.JsonString);
            return;
        }
        if (value.MySuggester != null)
        {
            serializer.Serialize(writer, value.MySuggester);
            return;
        }
        throw new Exception("Cannot marshal type CollationElements");
    }

    public static readonly SuggesterElementConverter Singleton = new SuggesterElementConverter();
}

public class AutocompleteConverter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
        Converters =
        {
            SuggesterElementConverter.Singleton
        }
    };
}

var results = JsonConvert.DeserializeObject<AutocompleteResultsInfo>(resultJson, AutocompleteConverter.Settings);

Many thanks for your help.

Kind Regerds, Wojciech

You could decode the "mySuggester" as a dictionary: public class Suggest

public class Suggest
{
    [JsonProperty("mySuggester")]
    public Dictionary<string, MySuggester> MySuggester { get; set; }
}

Then you'll be able to access the suggestions with the query string parameter:

var variablePropertyName = "Ext";

var result = JsonConvert.DeserializeObject<AutocompleteResultsInfo>(_json);

var suggestions = result.Suggest.MySuggester[variablePropertyName].Suggestions;

if you don't know the property name you could also look it up in the dictionary:

var variablePropertyName = result.Suggest.MySuggester.Keys.First();

Working example: https://dotnetfiddle.net/GIKwLs

Deserializing different JSON structures to the same C# class, But how do I deserialize the second JSON payload into an instance of that same class? Enter JsonConverter. Thankfully JSON.NET allows for a  How to read JSON into .NET objects (deserialize) To deserialize from a string or a file, call the JsonSerializer.Deserialize method. The following example reads JSON from a string and creates an instance of the WeatherForecast class shown earlier for the serialization example:

If you don't need to deserialize the whole json string you can use a JsonTextReader. Example:

private static IEnumerable<string> GetTerms(string json)
{
    using (JsonTextReader reader = new JsonTextReader(new StringReader(json)))
    {
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.PropertyName && reader.Value.Equals("term"))
            {
                string term = reader.ReadAsString();

                yield return term;
            }
        }
    }
}

Using the code:

string json = @"{
    ""responseHeader"": {
        ""zkConnected"": true,
        ""status"": 0,
        ""QTime"": 2
    },
    ""suggest"": {
        ""mySuggester"": {
            ""Ext"": {
                ""numFound"": 10,
                ""suggestions"": [
                    {
                        ""term"": ""Extra Community"",
                        ""weight"": 127,
                        ""payload"": """"
                    },
                    {
                        ""term"": ""External Video block"",
                        ""weight"": 40,
                        ""payload"": """"
                    },
                    {
                        ""term"": ""Migrate Extra"",
                        ""weight"": 9,
                        ""payload"": """"
                    }
                ]
            }
        }
    }
}";

IEnumerable<string> terms = GetTerms(json);

foreach (string term in terms)
{
    Console.WriteLine(term);
}

JsonPropertyAttribute name, This sample uses T:Newtonsoft.Json.JsonPropertyAttribute to change the names of properties when they are serialized to JSON. Thankfully JSON.NET allows for a lot of flexibility in how JSON objects are deserialize. I have written two blog posts on this before. To handle this particular scenario, I created a JsonConverter with a simple mapping table which maps the attributes of the second JSON payload to the attributes of the first JSON payload.

If you only need the object containing the term, and nothing else, you could work with the JSON values directly by using the JObject interface in JSON.Net.

var parsed = JObject.Parse(jsonString);
var usingLinq = (parsed["suggest"]["mySuggester"] as JObject)
    .Descendants()
    .OfType<JObject>()
    .Where(x => x.ContainsKey("term"));

var usingJsonPath = parsed.SelectTokens("$.suggest.mySuggester.*.*[?(@.term)]")
    .Cast<JObject>();

Json.NET, World-class JSON Serializer. Serialize and deserialize any .NET object with Json​.NET's powerful JSON serializer. LINQ to JSON. Create, parse, query and modify​  c# - Deserialize JSON array of different types - Stack Overflow. Let's say I have the following JSON array:[ { "type": "point", "x": 10, "y": 20 }, { "type": "circle", "x": 50, "y": 50, "radius": 200 }, { "type": "person", "first_name": "Linus", ". Stack Overflow. Products. Customers.

Migrate from Newtonsoft.Json to System.Text.Json, NET object models or other code changes. Deserialize JSON null literal to non-​nullable value types, ⚠️ Not supported, workaround, sample. Json.NET Documentation. Deserialize an Object. Deserialize with CustomCreationConverter. Deserialize JSON from a file. Populate an Object.

How to serialize and deserialize JSON using C#, Text.Json namespace to serialize to and deserialize from JSON in .NET. The difference is because the bytes (as UTF-8) don't need to be converted to strings  The JsonConverter is a helper class which can assist in converting other types than what Newtonsoft.Json comes with out of the box. They basically encompass the process of getting "json object -> .NET object" and back again. We'll be using one of these to map our types back and forth.

Using JSON.NET for dynamic JSON parsing, NET provides a robust JSON serializer that has both high level and low level ability to serialize and deserialize arbitrary JSON content dynamically - that map this data, without having to map the entire API to a C# data structure. can be useful for fully data driven JSON generation from other structures. Nowadays, we are dealing with JSON data mostly when receiving data in JSON format from a web service and getting data from it. To accomplish getting data from JSON or creating JSON text from a custom object we will use JSON serialization and deserialization in C#.