Newtonsoft JSON:如何序列化一些不是字符串,整数等的.NET对象...(如NetworkInterface)

时间:2015-12-19 06:18:48

标签: vb.net serialization json.net

我试图序列化我从System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()

获取的信息

GetAllNetworkInterfaces()返回NetworkInterface个对象的集合。序列化它基本上不会返回有用的信息。

    {
      "IsReceiveOnly": false,
      "Description": "TAP-Windows Adapter V9",
      "SupportsMulticast": true,
      "NetworkInterfaceType": 6,
      "OperationalStatus": 2,
      "Speed": 100000000,
      "Id": "{BCE79C39-232A-4483-AF64-1D26E3AA7C83}",
      "Name": "Ethernet"
    },
    etc...

每个NetworkInterface对象都有一个函数GetIPProperties,它返回一个IPInterfaceProperties对象,而该对象又有一个返回GetIPv4Properties()对象的IPv4InterfaceProperties函数。

我看到很多向类属性添加属性的示例,告诉Newtonsoft JSON序列化不是普通字符串,整数,布尔值等的属性......甚至序列化函数调用的结果,但是我&# 39; m难以理解如何为现有的.NET对象指出。

我当前和非常痛苦的解决方法是使用我想要的属性创建自己的MyNetworkInterface类,然后手动分配以下属性:

for each adapter as NetworkInterface in NetworkInterface.GetAllNetworkInterfaces()
  my_custom_network_interface_object.some_property = real_network_interface_object.some_property
  dim ip_properties() as IPInterfaceProperties = real_network_interface_object.GetIPProperties()
  dim gateway_info() as GatewayIPAddressInformationCollection = ip_properties.GatewayAddresses
  for gw in gateway_info
     my_custom_network_interface_object.gateway.add(gw.ToString())

似乎应该有更好的方法,我只是错过了它。

来自Python背景,我觉得在VB.NET中完全迷失了。 :)

1 个答案:

答案 0 :(得分:1)

要正确执行此操作,您首先需要定义一些自定义转换器类:

}

然后您可以将它们连接到默认设置:

Class NetworkInterfaceJsonConverter
    Inherits JsonConverter

    Public Overrides Function CanConvert(objectType As Type) As Boolean
        Return GetType(NetworkInterface).IsAssignableFrom(objectType)
    End Function

    Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)

        ' prevent infinite recursion by temporarily removing this converter
        serializer.Converters.Remove(Me)

        ' build a jObject, starting with the properties we already have
        Dim jObj = JObject.FromObject(value, serializer)

        ' add the results from the GetIPProperties call as a nested object
        Dim adapter As NetworkInterface = value
        Dim properties = adapter.GetIPProperties()
        jObj.Add("IPProperties", JObject.FromObject(properties))

        ' we can add the GetIPv4Properties results also
        If adapter.Supports(NetworkInterfaceComponent.IPv4) Then
            Dim ipv4Properties = properties.GetIPv4Properties()
            jObj.Add("IPv4Properties", JObject.FromObject(ipv4Properties))
        End If

        ' you can expand this here if you need results from other method calls

        ' finally, write the jObject to the writer
        jObj.WriteTo(writer)

        ' restore the converter
        serializer.Converters.Add(Me)

    End Sub

    Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
        Throw New NotImplementedException ' You can implement this if you have read usages
    End Function
End Class

Class IPAddressJsonConverter
    Inherits JsonConverter

    Public Overrides Function CanConvert(objectType As Type) As Boolean
        Return GetType(IPAddress).IsAssignableFrom(objectType)
    End Function

    Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)

        ' this one's pretty simple, but it's necessary to get the correct output
        Dim ipAddress As IPAddress = value
        writer.WriteValue(ipAddress.ToString())
    End Sub

    Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
        Throw New NotImplementedException ' You can implement this if you have read usages
    End Function
End Class

然后你可以正常转换:

JsonConvert.DefaultSettings =
    Function()
        Dim settings = New JsonSerializerSettings()
        settings.Converters.Add(New NetworkInterfaceJsonConverter())
        settings.Converters.Add(New IPAddressJsonConverter())
        Return settings
    End Function