小编Bri*_*ers的帖子

将JSON反序列化为对象

我有一些JSON:

{
    "foo" : [ 
        { "bar" : "baz" },
        { "bar" : "qux" }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我想将其反序列化为一个集合.我已经定义了这个类:

public class Foo
{
    public string bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是,以下代码不起作用:

 JsonConvert.DeserializeObject<List<Foo>>(jsonString);
Run Code Online (Sandbox Code Playgroud)

如何反序列化我的JSON?

c# json json.net

9
推荐指数
1
解决办法
1万
查看次数

为什么Json.Net在序列化时会在我的对象上调用Equals方法?

我在使用Newtonsoft.Json SerializeObject方法时遇到了一个错误.之前有人问过这个问题,但与Newtonsoft合作的人没有回答为什么会这样.

基本上,这样打电话时SerializeObject:

string json = Newtonsoft.Json.JsonConvert.SerializeObject(from, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
Run Code Online (Sandbox Code Playgroud)

Equals在我的类中覆盖了很多方法中的错误:

public override bool Equals(object obj)
{
    if (obj == null)
        return false;

    CapacityConfiguration cc = (CapacityConfiguration)obj; // <-- TypeCastException here; other Properties of the same class are sent in as parameter!
}
Run Code Online (Sandbox Code Playgroud)

当然,通过这样检查,我意识到修复起来很"容易":

public override bool Equals(object obj)
{
    if (obj is CapacityConfiguration == false)
        return false;

    CapacityConfiguration cc = (CapacityConfiguration)obj;
}
Run Code Online (Sandbox Code Playgroud)

但真正的问题是: 为什么Json.Net在类的Equals方法中发送其他类型的对象?更具体地说,Json.Net似乎在类中发送了许多其他属性,而不是相同类型的另一个对象.

对我来说,这完全是奇怪的.任何输入将不胜感激. …

c# json equals serializer json.net

9
推荐指数
1
解决办法
652
查看次数

使用JSON.NET库在JArray中查找节点(JObject)

我正在使用JSON.NET库.我创建了几个JObject并将它们添加到JArray中.

JArray array = new JArray();

JObject obj = new JObject();
obj.Add(new JProperty("text", "One"));
obj.Add(new JProperty("leaf", false));
array.Add(obj);

obj = new JObject();
obj.Add(new JProperty("text", "Two"));
obj.Add(new JProperty("leaf", false));
array.Add(obj);

obj = new JObject();
obj.Add(new JProperty("text", "Three"));
obj.Add(new JProperty("leaf", true));
array.Add(obj);
Run Code Online (Sandbox Code Playgroud)

现在我想找到一个JObject的文本(JProperty)Two.如何通过使用JProperty在JArray中找到JObject.

c# json json.net

8
推荐指数
1
解决办法
2万
查看次数

JsonConvert.DeserializeObject <>(string)为$ id属性返回null值

我正在使用System.Net.WebClient.DownloadString下载JSON.我收到了有效回复:

{
"FormDefinition": [
    {
        "$id":"4",
        "Class":558,
        "ClassDisplayLabel":"Punchworks",
        "Name":"Punchworks Form"
    },
    {
        "$id":"6",
        "Class":558,
        "ClassDisplayLabel":"Punchworks",
        "Name":"Punchworks Form test second"
    },
    {
        "$id":"46",
        "Class":558,
        "ClassDisplayLabel":"Punchworks",
        "Name":"any_Name"
    },
    {
        "$id":"47",
        "Class":558,
        "ClassDisplayLabel":"Punchworks",
        "Name":"Punchworks Form test second"
    },
    {
        "$id":"49",
        "Class":558,
        "ClassDisplayLabel":"Punchworks",
        "Name":"Testing Name ??´????? ???? ACEeišuu { [ ( ~ ! @ # "
    },
    {
        "$id":"50",
        "Class":558,
        "ClassDisplayLabel":"Punchworks",
        "Name":"something new"
    },
    {
        "$id":"56",
        "Class":558,
        "ClassDisplayLabel":"Punchworks",
        "Name":"Testing Name руÌÑÑкий 汉语漢語 ĄČĘėįšųū { [ ( ~ ! @ # "
    },
    {
        "$id":"57", …
Run Code Online (Sandbox Code Playgroud)

c# webclient json.net

8
推荐指数
1
解决办法
1万
查看次数

Json.Net在列表反序列化期间调用属性getter,导致重复项

我正在使用json.net来实现winform应用程序的memento模式.我正在使用memento在失败的数据库事务上回滚对象.我得到的问题是,当反序列化纪念品时,调用getter而不是setter.让我来证明:

class MyClass
{
    public int ID { get; set; }
    public string field1 { get; set; }
    public string field2 { get; set; }

    private List<SomeObject> _someObjects;
    public List<SomeObject> SomeObjects
    {
        get
        {
            if(_someObjects == null)
            {
                _someObjects = LoadSomeObjectsFromDB();
            }
            return _someObjects;
        }
        set
        {
            _someObjects = value;
        }
    }

    private List<AnotherObject> _anotherObjects;
    public List<AnotherObject> AnotherObjects
    {
        get
        {
            if(_anotherObjects == null)
            {
                _anotherObjects= LoadAnotherObjectsFromDB();
            }
            return _anotherObjects ;
        }
        set
        {
            _anotherObjects = value;
        } …
Run Code Online (Sandbox Code Playgroud)

c# json.net winforms json-deserialization

8
推荐指数
1
解决办法
3039
查看次数

如何删除 nbf 声明

一直在到处寻找答案,但似乎找不到适合我的答案。问题是我正在尝试在 c# 中使用 ASP.NET 构建 JWT 令牌。我遇到的问题是它在某处自动向我的声明添加了“nbf”声明,我似乎无法弄清楚如何将其删除,因为 API 主机不允许在令牌中使用它。下面是一段关于创建令牌的代码:

               var plainTextSecurityKey = "key";
            var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(plainTextSecurityKey));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey,
                Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


            var claimsIdentity = new ClaimsIdentity(new List<Claim>()
            {
                new Claim("iss", "smthing"),
                new Claim("sub", "smthing"),
                new Claim("iat", ToUnixTime(issued).ToString()),
                new Claim("exp",ToUnixTime(expire).ToString()),
                new Claim("aud", JsonConvert.SerializeObject(new[] { "ohlc" }).ToString())
            });

 claimsIdentity.TryRemoveClaim(claimsIdentity.FindFirst("nbf"));


            var securityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
            {
                Subject = claimsIdentity,
                SigningCredentials = signingCredentials,
            };


            securityTokenDescriptor.NotBefore = null;

            var tokenHandler = new JwtSecurityTokenHandler();
            var plainToken = tokenHandler.CreateToken(securityTokenDescriptor);
            var signedAndEncodedToken = tokenHandler.WriteToken(plainToken); …
Run Code Online (Sandbox Code Playgroud)

c# json.net jwt

8
推荐指数
1
解决办法
1803
查看次数

在Json.NET中将Dictionary <,>序列化为数组

如何使Json.NET序列化程序将IDictionary<,>实例序列化为具有键/值属性的对象数组?默认情况下,它将Key的值序列化为JSON对象的属性名称.

基本上我需要这样的东西:

[{"key":"some key","value":1},{"key":"another key","value":5}]
Run Code Online (Sandbox Code Playgroud)

代替:

{{"some key":1},{"another key":5}}
Run Code Online (Sandbox Code Playgroud)

我尝试添加KeyValuePairConverter到序列化程序设置但它没有任何效果.(我发现这个转换器被忽略的类型IDictionary<>,但因为它们是从其他图书馆接收,所以从改变我不能轻易改变我的对象的类型IDictionary<>,以ICollection<KeyValuePair<>>不选择我.)

json.net

7
推荐指数
1
解决办法
6280
查看次数

使用[JsonConverter]属性时,我的JsonConverter类中的StackOverflowException

我有一个测试类,我试图序列化:

public class Testing
{
    private string _name;
    private string _firstname = "firstname";
    public string _lastname;
    private DateTime _datenow = DateTime.Now;
    public DateTime _birthdate = DateTime.Now;

    public string Name { get { return _name; } set { _name = value; } }
}
Run Code Online (Sandbox Code Playgroud)

我使用自定义JsonConverter来处理测试类的序列化:

public class TestingConverter : JsonConverter
{
    private Type[] _types = new Type[] { typeof(Testing)};

    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> …
Run Code Online (Sandbox Code Playgroud)

.net json.net c#-4.0

7
推荐指数
1
解决办法
2887
查看次数

使用嵌套对象中的属性反序列化JSON

我如何轻松地将此JSON反序列化为OrderDto C#类?有某种方式可以通过属性来做到这一点吗?

JSON:

{
    "ExternalId": "123",
    "Customer": {
        "Name": "John Smith"
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

C#:

public class OrderDto
{
    public string ExternalId { get; set; }
    public string CustomerName { get; set; }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用JsonProperty属性,但无法使其正常工作。我的想法是写一个像这样的注释:

[JsonProperty("Customer/Name")]
public string CustomerName { get; set; }
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用。有任何想法吗?谢谢!:)

c# json json.net deserialization

7
推荐指数
2
解决办法
1万
查看次数

将 JSON 数组转换为 XML

我正在尝试将 JSON 转换为 XML。我的 JSON 包含一系列汽车,每辆车都有一系列功能:

[
    {
        "car": {
            "features": [{
                "code": "1"
            }, {
                "code": "2"
            }]
        }
    },
    {
        "car": {
            "features": [{
                "code": "3"
            }, {
                "code": "2"
            }]
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

我正在将其转换为 XML:

// the tag name for each top level element in the json array
var wrappedDocument = string.Format("{{ car: {0} }}", jsonResult);
// set the root tag name
return JsonConvert.DeserializeXmlNode(wrappedDocument, "cars");
Run Code Online (Sandbox Code Playgroud)

这是生成的 XML:

<cars>
   <car>
      <features>
        <code>1</code>
      </features>
      <features>
        <code>2</code>
      </features>
   </car>
   <car> …
Run Code Online (Sandbox Code Playgroud)

c# xml arrays json json.net

7
推荐指数
1
解决办法
7792
查看次数