1

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

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

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

编辑 我正在使用C#2.0 这是我正在使用的代码

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

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

4

2 回答 2

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;
于 2013-09-18T12:07:49.150 回答
0

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

试试这个 :

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

或者你也可以试试这个(假设你的是字典里面的字典)

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

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

于 2013-09-18T12:10:02.243 回答