TeamSirenix / odin-serializer

Fast, robust, powerful and extendible .NET serializer built for Unity
http://www.odininspector.com
Apache License 2.0
1.69k stars 193 forks source link

How to deserialize json string to array data ? #26

Closed sgamerw closed 5 years ago

sgamerw commented 5 years ago

How to deserialize json string to array data ?

[{"name": "J - Guide", "author": "H ft. Cb", "trial": "", "difficulty": "1", "json": "j-guide", "id": "50000"}, {"name": "J - Guide Ⅱ", "author": "Hoiyip", "trial": "", "difficulty": "1", "json": "j-guide-ii", "id": "59000"}]

and this is my model

[Serializable]
    public class SongLibItemModel
    {
        public string name;
        public string author;
        public string trial;
        public string difficulty;
        public string json;
        public string id;
    }

I try to run these

SerializationUtility.DeserializeValue<List<SongLibItemModel>>(libTextAsset.bytes, DataFormat.JSON);

but it returns null.

TorVestergaard commented 5 years ago

Odin is not a classical json deserializer in how it maps the json string to C# data - it needs the json to be annotated with a lot of metadata and be structured in a certain way to be able to reconstruct C# data from it, due to the particular features that Odin serializer needs to support (recursive references, type polymorphism, multiple target data formats, etc). As such, while your json string is perfectly valid json, Odin serializer cannot quite use it.

For deserializing your particular data, you'd be better served using Newtonsoft's Json.NET, a far more general-purpose json serializer, as you should only use Odin serializer to deserialize json data that it has itself serialized. Json support in Odin serializer is mainly intended for having an easily human-readable data format for debugging.

sgamerw commented 5 years ago

ok, got it, thanks.