Deserialization of JSON object by using DataContractJsonSerializer in C#

旧巷老猫 提交于 2019-12-10 23:43:33

问题


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

回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/17409655/deserialization-of-json-object-by-using-datacontractjsonserializer-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!