简体   繁体   中英

Deserialization of JSON object by using DataContractJsonSerializer in C#

I'm sure this question has been asked over and over again, but for some reason, I still can't manage to get this to work.

I want to deserialize a JSON object that contains a single member; a string array:

[{"idTercero":"cod_Tercero"}]

This is the class that I'm trying to deserialize into:

[DataContract]
public class rptaOk
{
    [DataMember]
    public string idTercero { get; set; }

    public rptaOk() { }

    public rptaOk(string idTercero)
    {
        this.idTercero = idTercero;
    }
}

This is the method that I try to deserialize:

public T Deserialise<T>(string json)
    {
        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            T result = (T)deserializer.ReadObject(stream);
            return result;
        }
    }

And so I try to fill the object:

rptaOk deserializedRpta = deserializarOk(rpta);

But for some reason, this returns ""

MessageBox.Show(deserializedRpta.idTercero);

Without any dependencies outside of the .net framework, you could do it this way

[DataContract(Name="rptaOk")]
public class RptaOk
{
    [DataMember(Name="idTercero")]
    public string IdTercero { get; set; }
}

[CollectionDataContract(Name="rptaOkList")]
public class RptaOkList : List<RptaOk>{}

var stream = new StreamReader(yourJsonObjectInStreamFormat);
var serializer = new DataContractSerializer(typeof(RptaOkList));
var result = (RptOkList) serializer.ReadObject(stream);

I think you're making this a lot more difficult than it needs to be. Firstly, your sample json and the class you're trying to deserialize into do not have an array of strings. They have a single property of type string. Secondly, why are you using this class DataContractJsonSerializer ? You're not doing anything with it that you can't get from a simple call to json.NET's generic deserialization method. I would remove all of your code except the class definition and replace it with this simple one liner;

 rptaOk[] myInstances = JsonConvert.DeserializeObject<rptaOk>(jsonString);

Also, no matter what the structure of your json is, if you have a class to correctly model it that method will correctly deserialize it. If you want to enforce some kind of contract I recommend using json schemas which json.NET also supports. If you use a schema it enforces a rigid contract, if you attempt to deserialize into an object there is something of an implicit contract. I don't know every scenario which will cause it to throw, but if your json is too far from the class definition it will. If your class has properties that don't appear in the json I believe they will just get initialized with the default values for that type.

EDIT: I just noticed your json is actually an array of objects. So you simply need to make the lhs of that assignment an array or rptaOk objects, rather than a singleton.

I don't know if your're wiling to change the library that you're using, but I use library "Newtonsoft.Json" to desserialize JSON objects, it's pretty easy to use

    [HttpPost]
    public void AddSell(string sellList)
    {
        var sellList = JsonConvert.DeserializeObject<List<Sell>>(sellListJson);
        BD.SaveSellList(sellList);
    }

As you can see you can deserialize a whole json object list to a List<> fo the type "Sell", an object that i've created... And, of course, you can do that to an array too. I don't know the correct syntax for this, but you can convert this list to an array afterwards

Hope this helps

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