简体   繁体   English

在C#中使用DataContractJsonSerializer反序列化JSON对象

[英]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; 我想反序列化包含单个成员的JSON对象; 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 没有.net框架之外的任何依赖,你可以这样做

[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. 首先,您的示例json和您尝试反序列化的类没有字符串数组。 They have a single property of type string. 它们具有string类型的单个属性。 Secondly, why are you using this class DataContractJsonSerializer ? 其次,为什么要使用这个类DataContractJsonSerializer You're not doing anything with it that you can't get from a simple call to json.NET's generic deserialization method. 你没有做任何事情,你不能从简单的调用json.NET的通用反序列化方法。 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. 此外,无论你的json的结构是什么,如果你有一个类来正确地建模它,那么该方法将正确地反序列化它。 If you want to enforce some kind of contract I recommend using json schemas which json.NET also supports. 如果你想强制执行某种合同我建议使用json.NET也支持的json模式。 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. 我不知道会导致它抛出的每个场景,但是如果你的json离类定义太远,它会。 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. 如果您的类具有未出现在json中的属性,我相信它们将使用该类型的默认值进行初始化。

EDIT: I just noticed your json is actually an array of objects. 编辑:我刚刚注意到你的json实际上是一个对象数组。 So you simply need to make the lhs of that assignment an array or rptaOk objects, rather than a singleton. 因此,您只需要将该赋值的lhs rptaOk数组或rptaOk对象,而不是单个。

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 我不知道你是否愿意改变你正在使用的库,但我使用库“Newtonsoft.Json”来反序列化JSON对象,它很容易使用

    [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. 正如您所看到的,您可以将整个json对象列表反序列化为类型为“Sell”的List <>,这是我创建的对象......当然,您也可以对数组执行此操作。 I don't know the correct syntax for this, but you can convert this list to an array afterwards 我不知道这个的正确语法,但您可以将此列表转换为数组

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 C# 中使用 DataContractJsonSerializer 使用 List&lt;&gt; 反序列化 JSON 对象 - Deserialization of JSON object with List<> using DataContractJsonSerializer in C# 使用C#中的DataContractJsonSerializer将子字段作为字符串反序列化JSON对象 - Deserialization of JSON object with sub field as string using DataContractJsonSerializer in C# 使用DataContractJsonSerializer,将JSON字符串反序列化为具有列表和接口作为属性的C#对象 - Using DataContractJsonSerializer, deserialization of JSON string into C# object which has list & interface as properties 使用DataContractJsonSerializer对JSON对象进行部分反序列化 - Partial deserialization of JSON object by using DataContractJsonSerializer 使用DataContractJsonSerializer将Json反序列化为C#动态对象 - Deserialize Json into a C# dynamic object using DataContractJsonSerializer C#中的Json对象反序列化 - Json Object Deserialization in c# DataContractJsonSerializer动态对象反序列化 - DataContractJsonSerializer dynamic object deserialization 使用C#DataContractJsonSerializer解析JSON命名数组 - Parse JSON named array using C# DataContractJsonSerializer C#-使用DataContractJsonSerializer将JSON字符串反序列化为Enum [] - C# - Deserialize JSON string to Enum[] using DataContractJsonSerializer 将 C# 中的 JSON 反序列化为 object 用于 ZDB974238714CA8DE634A7CE1D083A1 - Deserialization of JSON in C# into an object for API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM