反序列化json值,其中属性具有":"

时间:2013-09-12 13:49:24

标签: c# json c#-2.0

我正在使用REST服务,它返回的json格式如下:

{
"ea:productionId": "123",
....
}

如何在服务器端创建一个与此类json相对应的类进行解析?我正在使用c#。

修改  我正在使用 C#2.0 这是我正在使用的代码

JavaScriptSerializer serializer = new JavaScriptSerializer();
        JsonClass result= serializer.Deserialize<JsonClass>(jsonresult);

JsonClass是我创建的类,其中的字段对应于jsonresult中的属性。 问题是,我无法创建名为ea:productionId的属性,因为它包含:

2 个答案:

答案 0 :(得分:2)

您在问题中显示的内容是无效的JSON。我想你的意思是:

{
    "ea:productionId": "123",
    ....
}

使用Json.NET序列化程序在您的模型上使用[DataContract][DataMember]属性很容易实现:

[DataContract]
public class JsonClass
{
    [DataMember(Name = "ea:productionId")]
    public string ProductId { get; set; }
}

然后:

JsonClass result = JsonConvert.DeserializeObject<JsonClass>(jsonresult);

如果您不想使用第三方JSON序列化程序,则可以使用内置的DataContractJsonSerializer类,该类也遵循DataContract和DataMember属性:

var serializer = new DataContractJsonSerializer(typeof(JsonClass));
byte[] data = Encoding.UTF8.GetBytes(jsonresult);
using (var stream = new MemoryStream(data))
{
    var result = (JsonClass)serializer.ReadObject(stream);
}

更新:

看起来您使用的是.NET 2.0,并且不能依赖于较新的序列化程序。使用JavaScriptSerializer,您可以编写自定义转换器:

public class MyJavaScriptConverter : JavaScriptConverter
{
    private static readonly Type[] supportedTypes = new[] { typeof(JsonClass) };

    public override IEnumerable<Type> SupportedTypes
    {
        get { return supportedTypes; }
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (type == typeof(JsonClass))
        {
            var result = new JsonClass();
            object productId;
            if (dictionary.TryGetValue("ea:productionId", out productId))
            {
                result.ProductId = serializer.ConvertToType<string>(productId);
            }

            ... so on for the other properties

            return result;
        }

        return null;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

然后:

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new MyJavaScriptConverter() });
var result = serializer.Deserialize<JsonClass>(jsonresult);

或者你可以使用弱类型字典而不是模型:

var serializer = new JavaScriptSerializer();
var res = (IDictionary<string, object>)serializer.DeserializeObject(jsonresult);
string productId = res["ea:productionId"] as string;

答案 1 :(得分:0)

json实际上类似于python中的字典(键值对)。你不能在没有引号的情况下写密钥。您的密钥实际上应该是一个字符串,您可以通过该字符串引用其值。你的json是无效的。

试试这个:

{
"ea:productionId": "123",
....
}

或者您也可以尝试这个(假设您的字典是字典中的字典)

{
"ea":{"productionId": "123",}
....
}

因此,要访问值“123”,请使用["ea"]["productionId"]