反序列化JSON在C#中使用非法字符变量 [英] deserialize json in C# with illegal variable characters

查看:407
本文介绍了反序列化JSON在C#中使用非法字符变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个.NET库(使用Newtonsoft)与REST服务交互,我有多数民众赞成返回JSON服务,但JSON id字段被称为'的$ id'。所以,我不能只建立在我的C#数据类对应的$ id属性。我试图用类似

I'm writing a .NET library (using Newtonsoft) that interacts with a REST service, and I have a service that's returning json, but the json id field is called '$id'. So I can't just create a corresponding $id property in my C# data class. I tried to use something like

    [JsonObject(MemberSerialization.OptOut)]
    public class DocData
    {
        [JsonProperty("$id")]
        public string id { get; set; }

        public string Name { get; set; }
    }

不过,虽然名字被分配,id属性没有。任何人都知道如何映射此JSON关键.NET?

but while Name gets assigned, the id property does not. Anyone know how to map this json key to .NET?

感谢

推荐答案

看起来这是JSON.NET的错误,我想你应该的报告。它工作正常,在LINQPad任何属性名称,除非的$ id

It looks like this is a bug in JSON.NET, and I think you should report it. It works fine in LINQPad for any property name except $id.

void Main()
{
    var s = JsonConvert.SerializeObject(new DocData{id = "hi", Name = "world"}).Dump();
    JsonConvert.DeserializeObject<DocData>(s).Dump();
}

public class DocData
{
    // [JsonProperty("i$d")] // this would work 
    // [JsonProperty("_id")] // as would this
    // [JsonProperty("$name")] // and even this
    [JsonProperty("$id")] // but this fails
    public string id { get; set; }

    public string Name { get; set; }
}

显然Json.NET使用的$ id 为保留字,帮助其对象引用处理。

Evidently Json.NET uses $id as a reserved word to help it deal with object references.

    var dd = new DocData{id = "hi", Name = "world"};
    JsonConvert.SerializeObject(new[]{dd, dd}, new JsonSerializerSettings{PreserveReferencesHandling = PreserveReferencesHandling.Objects}).Dump();
// Output: [{"$id":"1","$id":"hi","Name":"world"},{"$ref":"1"}]

不过,现在看来似乎应该让你,如果你不使用的参考处理捕获的$ id 属性。

作为一种变通方法,您可以解析为一个JObject,并直接拉动特性的:

As a workaround, you can parse it into a JObject, and pull the property out directly:

    var id = JObject.Parse(s)["$id"];
    var obj = JsonConvert.DeserializeObject<DocData>(s);
    obj.id = id;

这篇关于反序列化JSON在C#中使用非法字符变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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