您在问题中显示的内容是无效的 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;