Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

c# - How to deserialize an array of values with a fixed schema to a strongly typed data class?

I am having some trouble figuring out a clean (as possible) way to deserialize some JSON data in a particular format. I want to deserialize the data to strongly typed data object classes, pretty flexible regarding the specifics of this. Here is an example of what the data looks like:

{
    "timestamp": 1473730993,
    "total_players": 945,
    "max_score": 8961474,
    "players": {
            "Player1Username": [
            121,
            "somestring",
            679900,
            5,
            4497,
            "anotherString",
            "thirdString",
            "fourthString",
            123,
            22,
            "YetAnotherString"],
        "Player2Username": [
            886,
            "stillAstring",
            1677,
            1,
            9876,
            "alwaysAstring",
            "thirdString",
            "fourthString",
            876,
            77,
            "string"]
        }
}

The specific parts I am unsure about are:

  1. Would the collection of players be considered a dictionary? The username could serve as the key, but the value is throwing me off since it would be a mixed collection of string and integer values.
  2. A player is comprised entirely of unnamed values. I have pretty much always worked with JSON data that had named properties and values (ex. timestamp, total_players, etc. at the very top)

Say I have a top level class like this:

public class ScoreboardResults
{
    public int timestamp { get; set; }
    public int total_players { get; set; }
    public int max_score { get; set; }
    public List<Player> players { get; set; }
}

What would the Player object look like given that it is basically a key/value with the username serving as the key, and the value being a collection of mixed integers and strings? The data for each player element is always in the same order, so I know that the first value in the collection is their UniqueID, the second value is a player description, etc. I would like the player class to be something like this:

public class Player
{
    public string Username { get; set; }
    public int UniqueID { get; set; }
    public string PlayerDescription { get; set; }
    ....
    ....
    .... Following this pattern for all of the values in each player element
    ....
    ....
}

I am sure this is a pretty straightforward thing to do using JSON.NET, which is why I wanted to avoid any of the ideas I had on how to accomplish this. What I came up with would have been un-elegant and probably error prone to some degree during the serialization process.

EDIT

Here are the classes that get generated when using the past as JSON classes as suggested by snow_FFFFFF:

public class Rootobject
{
    public int timestamp { get; set; }
    public int total_players { get; set; }
    public int max_score { get; set; }
    public Players players { get; set; }
}

public class Players
{
    public object[] Player1Username { get; set; }
    public object[] Player2Username { get; set; }
}

What is not clear to me is how do I deserialize the JSON data in the "players" element as a List with Player1Username being a simple string property on the Player object. As for the collection of intermixed strings and integers, I am confident I can get those into individual properties on the Player object without issue.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The converter from Deserializing JSON in Visual Basic .NET should do what you need, suitably translated from VB.NET to c#:

public class ObjectToArrayConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(T) == objectType;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var objectType = value.GetType();
        var contract = serializer.ContractResolver.ResolveContract(objectType) as JsonObjectContract;
        if (contract == null)
            throw new JsonSerializationException(string.Format("invalid type {0}.", objectType.FullName));
        writer.WriteStartArray();
        foreach (var property in SerializableProperties(contract))
        {
            var propertyValue = property.ValueProvider.GetValue(value);
            if (property.Converter != null && property.Converter.CanWrite)
                property.Converter.WriteJson(writer, propertyValue, serializer);
            else
                serializer.Serialize(writer, propertyValue);
        }
        writer.WriteEndArray();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var contract = serializer.ContractResolver.ResolveContract(objectType) as JsonObjectContract;
        if (contract == null)
            throw new JsonSerializationException(string.Format("invalid type {0}.", objectType.FullName));

        if (reader.MoveToContentAndAssert().TokenType == JsonToken.Null)
            return null;
        if (reader.TokenType != JsonToken.StartArray)
            throw new JsonSerializationException(string.Format("token {0} was not JsonToken.StartArray", reader.TokenType));

        // Not implemented: JsonObjectContract.CreatorParameters, serialization callbacks, 
        existingValue = existingValue ?? contract.DefaultCreator();

        using (var enumerator = SerializableProperties(contract).GetEnumerator())
        {
            while (true)
            {
                switch (reader.ReadToContentAndAssert().TokenType)
                {
                    case JsonToken.EndArray:
                        return existingValue;

                    default:
                        if (!enumerator.MoveNext())
                        {
                            reader.Skip();
                            break;
                        }
                        var property = enumerator.Current;
                        object propertyValue;
                        // TODO:
                        // https://www.newtonsoft.com/json/help/html/Properties_T_Newtonsoft_Json_Serialization_JsonProperty.htm
                        // JsonProperty.ItemConverter, ItemIsReference, ItemReferenceLoopHandling, ItemTypeNameHandling, DefaultValue, DefaultValueHandling, ReferenceLoopHandling, Required, TypeNameHandling, ...
                        if (property.Converter != null && property.Converter.CanRead)
                            propertyValue = property.Converter.ReadJson(reader, property.PropertyType, property.ValueProvider.GetValue(existingValue), serializer);
                        else
                            propertyValue = serializer.Deserialize(reader, property.PropertyType);
                        property.ValueProvider.SetValue(existingValue, propertyValue);
                        break;
                }
            }
        }
    }

    static IEnumerable<JsonProperty> SerializableProperties(JsonObjectContract contract)
    {
        return contract.Properties.Where(p => !p.Ignored && p.Readable && p.Writable);
    }
}

public static partial class JsonExtensions
{
    public static JsonReader ReadToContentAndAssert(this JsonReader reader)
    {
        return reader.ReadAndAssert().MoveToContentAndAssert();
    }

    public static JsonReader MoveToContentAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (reader.TokenType == JsonToken.None)       // Skip past beginning of stream.
            reader.ReadAndAssert();
        while (reader.TokenType == JsonToken.Comment) // Skip past comments.
            reader.ReadAndAssert();
        return reader;
    }

    public static JsonReader ReadAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (!reader.Read())
            throw new JsonReaderException("Unexpected end of JSON stream.");
        return reader;
    }
}

Next, add the converter to your Player class, and indicate the order of each property using JsonPropertyAttribute.Order:

[JsonConverter(typeof(ObjectToArrayConverter<Player>))]
public class Player
{
    [JsonProperty(Order = 1)]
    public int UniqueID { get; set; }
    [JsonProperty(Order = 2)]
    public string PlayerDescription { get; set; }
    // Other fields as required.
}

Then finally, declare your root object as follows:

public class ScoreboardResults
{
    public int timestamp { get; set; }
    public int total_players { get; set; }
    public int max_score { get; set; }
    public Dictionary<string, Player> players { get; set; }
}

Note that I have moved Username out of the Player class and into the dictionary, as a key.

Note that data contract attributes can be used instead of Newtonsoft attributes to specify order:

[JsonConverter(typeof(ObjectToArrayConverter<Player>))]
[DataContract]
public class Player
{
    [DataMember(Order = 1)]
    public int UniqueID { get; set; }
    [DataMember(Order = 2)]
    public string PlayerDescription { get; set; }
    // Other fields as required.
}

Demo fiddles here, here and here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...