如何将JSON反序列化为对象属性(使用DataContractJsonSerializer) [英] How to deserialize JSON to object property (using DataContractJsonSerializer)

查看:245
本文介绍了如何将JSON反序列化为对象属性(使用DataContractJsonSerializer)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实有这些JSON文本反序列化(它们是更大结构的一部分,只是为了保持简单):



I do have these JSON text to deserialize (they are part of bigger structure, just to keep it simple):

{"name":"whatever","value":0}
{"name":"objectProperty","value":{"A":1,"B":2,"C":3,"D":4}}





当我想要反序列化为C#对象时:



when I do want to deserialize into the C# object:

public class Rootobject
{
    public string name { get; set; }
    public int value { get; set; }
}





我将获得第一种情况:



I will get in 1st case:

whatever : 0


我得到的第二种情况是



in the second case I get:

objectProperty : {object}





问题是我无法从



the problem is that I'm not able to get any value from the

{object}

获得任何价值。



当我使用这个C#类进行反序列化时:

.

when I do use this C# class to deserialize:

public class Rootobject
{
    public string name { get; set; }
    public Value value { get; set; }
}

public class Value
{
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
    public int D { get; set; }
}





我会收到错误:



I will get an error:

Expecting state 'Element'.. Encountered 'Text'  with name '', namespace ''.





有没有办法怎么样告诉反序列化器它应该反序列化哪个类?或者任何想法如何解决这个问题?



thx,

R.



Is there a way how to tell deserializer to which class it should deserialize? Or any idea how to solve this problem?

thx,
R.

推荐答案

[DataContract]

注释添加到您的班级,并将

annotation to your class and

[DataMember]

注释添加到您的班级properties

annotation to you class properties

[DataContract]
    internal class Person
    {
        [DataMember]
        internal string name;

        [DataMember]
        internal int age;
    }


我的解决方案是使用 http:/ /www.newtonsoft.com/json [ ^ ]而不是标准系统运行时序列化。



这个库将复杂内容放在字符串表示中,这对我来说已经足够了。
Solution for me is to use http://www.newtonsoft.com/json[^] instead of standard system runtime serialization.

this library puts "complex content" in string representation which is enough for me for now.


这篇关于如何将JSON反序列化为对象属性(使用DataContractJsonSerializer)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆