如何使用空属性名称调用对象属性?

时间:2022-04-20 07:20:48

I have the following JSON and I have no control over it since it comes from an external API:

我有以下JSON,我无法控制它,因为它来自外部API:

    {
  "user_id": "something_name",
  "devices": {
    "": {
      "sessions": [
        {
          "connections": [
            {
              "ip": "225.225.225.225",
              "user_agent": "something",
              "last_seen": 1504266816737
            }
        }
      ]
    }
  }
}

I am using a JSON deserializer(JSON.Net) to make it into a dynamic object.

我正在使用JSON反序列化器(JSON.Net)将其变为动态对象。

dynamic values = JsonConvert.DeserializeObject<dynamic>(mes);

The thing is, one of the json key is an empty string "". Now I can't seem to call the property as such:

问题是,其中一个json键是一个空字符串“”。现在我似乎无法像这样调用该属性:

values.devices.<the empty string part>.sessions.connections

How do I call things below it when one of the top key is empty? Doing devices..sessions did not work.

当其中一个顶键为空时,如何调用它下方的内容?做设备..会话没有用。

3 个解决方案

#1


5  

You can use square bracket syntax to access the property with the empty key. For example:

您可以使用方括号语法使用空键访问该属性。例如:

dynamic ip = values.devices[""].sessions[0].connections[0].ip;

Fiddle: https://dotnetfiddle.net/H4orMZ

小提琴:https://dotnetfiddle.net/H4orMZ

#2


2  

The first issue I discovered: Your sample suffers from unbalanced brackets:
After "connections": [ comes no closing ]

我发现的第一个问题:你的样本遭受不平衡的括号:在“连接”之后:[没有关闭]

Anyways, it is doable:

无论如何,它是可行的:

...using a dynamic object like that:

...使用这样的动态对象:

dynamic values = JsonConvert.DeserializeObject<dynamic>(json);
var ip = values.devices[""].sessions[0].connections[0].ip;

...with a custom class definitions as shown below:

...具有自定义类定义,如下所示:

public class RootObject
{public string user_id { get; set; }
    public Dictionary<string, Devices> devices { get; set; }
}
public class Devices
{
    public List<Session> sessions { get; set; }
}
public class Session
{
    public List<Connections> connections { get; set; }
}
public class Connections
{
    public string ip { get; set; }
    public string user_agent { get; set; }
    public long last_seen { get; set; }
}

So, the Devices Key is an empty string - but that's fine.

因此,Devices Key是一个空字符串 - 但这没关系。

Try it live here. Output:

试试吧。输出:

Deserializing json...
Success!
  Device Key   #: 
  Device Value #: Devices
            IP #: 225.225.225.225 (just a sample sub-property)

using System;
using Newtonsoft.Json;
using System.Collections.Generic;

Full code:

完整代码:

public class Program
{
    public static void Main()
    {
        string json = @"{
                          ""user_id"": ""something_name"",
                          ""devices"": {
                            """": {
                              ""sessions"": [
                                {
                                  ""connections"": [
                                    {
                                      ""ip"": ""225.225.225.225"",
                                      ""user_agent"": ""something"",
                                      ""last_seen"": 1504266816737
                                    }
                                  ]
                                }
                              ]
                            }
                          }
                        }";

        Console.WriteLine("Deserializing json...");

        //dynamic values = JsonConvert.DeserializeObject<dynamic>(json);
        //var ip = values.devices[""].sessions[0].connections[0].ip;

        RootObject o = JsonConvert.DeserializeObject<RootObject>(json, new JsonSerializerSettings
        {
            MissingMemberHandling = MissingMemberHandling.Ignore, 
            NullValueHandling = NullValueHandling.Ignore //these settings are not important here
        });
        Console.WriteLine("Success!");
        foreach (var dev in o.devices)
        {
            Console.WriteLine("  Device Key   #: {0}", dev.Key);
            Console.WriteLine("  Device Value #: {0}", dev.Value);
            Console.WriteLine("            IP #: {0}", dev.Value.sessions[0].connections[0].ip);
        }
    }
}

public class RootObject
{public string user_id { get; set; }
    public Dictionary<string, Devices> devices { get; set; }
}
public class Devices
{
    public List<Session> sessions { get; set; }
}
public class Session
{
    public List<Connections> connections { get; set; }
}
public class Connections
{
    public string ip { get; set; }
    public string user_agent { get; set; }
    public long last_seen { get; set; }
}

#3


-3  

The best way to solve this problem is to modify the mes string like :

解决此问题的最佳方法是修改mes字符串,如:

string modifiedmes = mes.Replace("","prop");

dynamic values = JsonConvert.DeserializeObject<dynamic>(modifiedmes);

I guess then you will be able to access

我想那时你就可以访问了

values.devices.prop.sessions.connections

#1


5  

You can use square bracket syntax to access the property with the empty key. For example:

您可以使用方括号语法使用空键访问该属性。例如:

dynamic ip = values.devices[""].sessions[0].connections[0].ip;

Fiddle: https://dotnetfiddle.net/H4orMZ

小提琴:https://dotnetfiddle.net/H4orMZ

#2


2  

The first issue I discovered: Your sample suffers from unbalanced brackets:
After "connections": [ comes no closing ]

我发现的第一个问题:你的样本遭受不平衡的括号:在“连接”之后:[没有关闭]

Anyways, it is doable:

无论如何,它是可行的:

...using a dynamic object like that:

...使用这样的动态对象:

dynamic values = JsonConvert.DeserializeObject<dynamic>(json);
var ip = values.devices[""].sessions[0].connections[0].ip;

...with a custom class definitions as shown below:

...具有自定义类定义,如下所示:

public class RootObject
{public string user_id { get; set; }
    public Dictionary<string, Devices> devices { get; set; }
}
public class Devices
{
    public List<Session> sessions { get; set; }
}
public class Session
{
    public List<Connections> connections { get; set; }
}
public class Connections
{
    public string ip { get; set; }
    public string user_agent { get; set; }
    public long last_seen { get; set; }
}

So, the Devices Key is an empty string - but that's fine.

因此,Devices Key是一个空字符串 - 但这没关系。

Try it live here. Output:

试试吧。输出:

Deserializing json...
Success!
  Device Key   #: 
  Device Value #: Devices
            IP #: 225.225.225.225 (just a sample sub-property)

using System;
using Newtonsoft.Json;
using System.Collections.Generic;

Full code:

完整代码:

public class Program
{
    public static void Main()
    {
        string json = @"{
                          ""user_id"": ""something_name"",
                          ""devices"": {
                            """": {
                              ""sessions"": [
                                {
                                  ""connections"": [
                                    {
                                      ""ip"": ""225.225.225.225"",
                                      ""user_agent"": ""something"",
                                      ""last_seen"": 1504266816737
                                    }
                                  ]
                                }
                              ]
                            }
                          }
                        }";

        Console.WriteLine("Deserializing json...");

        //dynamic values = JsonConvert.DeserializeObject<dynamic>(json);
        //var ip = values.devices[""].sessions[0].connections[0].ip;

        RootObject o = JsonConvert.DeserializeObject<RootObject>(json, new JsonSerializerSettings
        {
            MissingMemberHandling = MissingMemberHandling.Ignore, 
            NullValueHandling = NullValueHandling.Ignore //these settings are not important here
        });
        Console.WriteLine("Success!");
        foreach (var dev in o.devices)
        {
            Console.WriteLine("  Device Key   #: {0}", dev.Key);
            Console.WriteLine("  Device Value #: {0}", dev.Value);
            Console.WriteLine("            IP #: {0}", dev.Value.sessions[0].connections[0].ip);
        }
    }
}

public class RootObject
{public string user_id { get; set; }
    public Dictionary<string, Devices> devices { get; set; }
}
public class Devices
{
    public List<Session> sessions { get; set; }
}
public class Session
{
    public List<Connections> connections { get; set; }
}
public class Connections
{
    public string ip { get; set; }
    public string user_agent { get; set; }
    public long last_seen { get; set; }
}

#3


-3  

The best way to solve this problem is to modify the mes string like :

解决此问题的最佳方法是修改mes字符串,如:

string modifiedmes = mes.Replace("","prop");

dynamic values = JsonConvert.DeserializeObject<dynamic>(modifiedmes);

I guess then you will be able to access

我想那时你就可以访问了

values.devices.prop.sessions.connections