handling name space changes during deserialization of JSON String

徘徊边缘 提交于 2019-12-20 05:02:12

问题


I have 2 applications that are communicate amongst each other with the help of a redis Server, In my first application i am able to serialize and de serialize and object of the following type

   {
 "$type": "System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib],   [OPCMessagingService.Resource, OPCMessagingService]], mscorlib",
 "71": {
"$type": "OPCMessagingService.Resource, OPCMessagingService",
"SiteID": 2,
"ResourceID": 71,
"ProcessOrder": "001000380873",
"CurrentStatus": 0,
"CycleTime": 55,
"DeviceList": [
  {
    "$type": "OPCMessagingService.StackLight, OPCMessagingService",
    "ResourceId": 71,
    "DeviceIp": "10.142.117.7",
    "ComPort": "COM14"
  },
  {
    "$type": "OPCMessagingService.LED, OPCMessagingService",
    "ResourceId": 71,
    "DeviceIp": "10.142.117.3",
    "ComPort": "COM10",
    "IsMessageDelivered": false,
    "RetryCount": 3,
    "IsRetryRequired": true,
    "_messageHeader": ":*HF601011471",
    "_messageText": "DISPOMELT 5245 BULK - 0020 -投矿物油,树脂,液体树脂和橡胶",
    "_delayedMessageText": "",
    "_counter": 0
  }
],
"UpdateDate": 20150120,
"UpdateTime": 231506,
"CurrentDate": 20150124,
"CurrentTime": 151513,
"CurrentMessage": "DISPOMELT 5245 BULK - 0020 -投矿物油,树脂,液体树脂和橡胶"
  },
  "72": {
"$type": "OPCMessagingService.Resource, OPCMessagingService",
"SiteID": 2,
"ResourceID": 72,
"ProcessOrder": "001000380874",
"CurrentStatus": 0,
"CycleTime": 60,
"DeviceList": [
  {
    "$type": "OPCMessagingService.LED, OPCMessagingService",
    "ResourceId": 72,
    "DeviceIp": "10.142.117.98",
    "ComPort": "COM100",
    "IsMessageDelivered": false,
    "RetryCount": 3,
    "IsRetryRequired": true,
    "_messageHeader": ":*HF601011471",
    "_messageText": "DISPOMELT 5245 BULK - 0050 -熔树脂",
    "_delayedMessageText": "",
    "_counter": 0
  },
  {
    "$type": "OPCMessagingService.LED, OPCMessagingService",
    "ResourceId": 72,
    "DeviceIp": "10.142.117.4",
    "ComPort": "COM11",
    "IsMessageDelivered": false,
    "RetryCount": 3,
    "IsRetryRequired": true,
    "_messageHeader": ":*HF601011471",
    "_messageText": "DISPOMELT 5245 BULK - 0050 -熔树脂",
    "_delayedMessageText": "",
    "_counter": 0
  },
  {
    "$type": "OPCMessagingService.StackLight, OPCMessagingService",
    "ResourceId": 72,
    "DeviceIp": "10.142.117.8",
    "ComPort": "COM15"
  },
  {
    "$type": "OPCMessagingService.StackLight, OPCMessagingService",
    "ResourceId": 72,
    "DeviceIp": "10.142.117.97",
    "ComPort": "COM101"
  }
],
"UpdateDate": 20150120,
"UpdateTime": 231534,
"CurrentDate": 20150124,
"CurrentTime": 151513,
"CurrentMessage": "DISPOMELT 5245 BULK - 0050 -熔树脂"
  },
  "73": {
"$type": "OPCMessagingService.Resource, OPCMessagingService",
"SiteID": 2,
"ResourceID": 73,
"ProcessOrder": "001000375454",
"CurrentStatus": 0,
"CycleTime": 60,
"DeviceList": [
  {
    "$type": "OPCMessagingService.LED, OPCMessagingService",
    "ResourceId": 73,
    "DeviceIp": "10.142.117.5",
    "ComPort": "COM12",
    "IsMessageDelivered": false,
    "RetryCount": 3,
    "IsRetryRequired": true,
    "_messageHeader": ":*HF601011471",
    "_messageText": "XHC 9228 BULK - 0050 -熔树脂",
    "_delayedMessageText": "",
    "_counter": 0
  },
  {
    "$type": "OPCMessagingService.StackLight, OPCMessagingService",
    "ResourceId": 73,
    "DeviceIp": "10.142.117.9",
    "ComPort": "COM16"
  }
],
"UpdateDate": 20150120,
"UpdateTime": 223043,
"CurrentDate": 20150124,
"CurrentTime": 151513,
"CurrentMessage": "XHC 9228 BULK - 0050 -熔树脂"
  },
  "74": {
"$type": "OPCMessagingService.Resource, OPCMessagingService",
"SiteID": 2,
"ResourceID": 74,
"ProcessOrder": "001000375455",
"CurrentStatus": 0,
"CycleTime": 40,
"DeviceList": [
  {
    "$type": "OPCMessagingService.LED, OPCMessagingService",
    "ResourceId": 74,
    "DeviceIp": "10.142.117.2",
    "ComPort": "COM9",
    "IsMessageDelivered": false,
    "RetryCount": 3,
    "IsRetryRequired": true,
    "_messageHeader": ":*HF601011471",
    "_messageText": "XHC 9228 BULK - 0040 -投树脂和剩料:",
    "_delayedMessageText": "",
    "_counter": 0
  },
  {
    "$type": "OPCMessagingService.StackLight, OPCMessagingService",
    "ResourceId": 74,
    "DeviceIp": "10.142.117.1",
    "ComPort": "COM5"
  }
],
"UpdateDate": 20150120,
"UpdateTime": 224143,
"CurrentDate": 20150124,
"CurrentTime": 151513,
"CurrentMessage": "XHC 9228 BULK - 0040 -投树脂和剩料:"
  },
  "75": {
"$type": "OPCMessagingService.Resource, OPCMessagingService",
"SiteID": 2,
"ResourceID": 75,
"ProcessOrder": "001000375456",
"CurrentStatus": 0,
"CycleTime": 50,
"DeviceList": [
  {
    "$type": "OPCMessagingService.StackLight, OPCMessagingService",
    "ResourceId": 75,
    "DeviceIp": "10.142.117.10",
    "ComPort": "COM17"
  },
  {
    "$type": "OPCMessagingService.LED, OPCMessagingService",
    "ResourceId": 75,
    "DeviceIp": "10.142.117.6",
    "ComPort": "COM13",
    "IsMessageDelivered": false,
    "RetryCount": 3,
    "IsRetryRequired": true,
    "_messageHeader": ":*HF601011471",
    "_messageText": "XHC 9228 BULK - 0020 -投矿物油和橡胶、抗氧剂,升温",
    "_delayedMessageText": "",
    "_counter": 0
  }
],
"UpdateDate": 20150120,
"UpdateTime": 225331,
"CurrentDate": 20150124,
"CurrentTime": 151513,
"CurrentMessage": "XHC 9228 BULK - 0020 -投矿物油和橡胶、抗氧剂,升温"
 }
 }

I able serialize this and de serialize this in one application but when i try to de serialize this in another application which obviously has a different name space. and i get an exception

Error resolving type specified in JSON 'System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib],[OPCMessagingService.Resource, OPCMessagingService]], mscorlib'. Path '$type', line 1, position 138.

I have tried to do the following while de serializing the Json String in another application and it does not work what else can i do to de serialize this object

 public static T GetRedisKeyValue<T>(string key)
    {
        if (key.Trim().Length > 0)
        {
            GetSentinelMaster();
            using (ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect(GetRedisConfiguraion()))
            {
                IDatabase redisDB = redisClient.GetDatabase(); // Getting database connection
                string temp = redisDB.StringGet(key);
                Type type = typeof(T);
                JObject jsonObject = JObject.Parse(temp);
                jsonObject["$type"] = type.FullName + ", " + type.Assembly.FullName;
               // JsonConvert.DeserializeObject<T>(temp);
                return JsonConvert.DeserializeObject<T>(temp, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full });
            }
        }
        return default(T);
    }

What else can i do to achieve this.?


回答1:


The format of the "$type" is officially hardcoded to include the CLR namespace of the sending system. So, you can either:

  1. Rename your CLR namespaces to match those of the sending system, or

  2. Subclass the DefaultSerializationBinder and use it to rename the CLR namespace names during deserialization by setting it in the JsonSerializerSettings.Binder.

The following is a first cut at doing this:

public class NamespaceMappingSerializationBinder : DefaultSerializationBinder
{
    public string FromNamespace { get; set; }

    public string ToNamespace { get; set; }

    public override Type BindToType(string assemblyName, string typeName)
    {
        string fixedTypeName;
        if (FromNamespace != null && ToNamespace != null)
        {
            fixedTypeName = typeName.Replace(FromNamespace, ToNamespace);
        }
        else
        {
            fixedTypeName = typeName;
        }
        var type = base.BindToType(assemblyName, fixedTypeName);
        return type;
    }
}

Then, when you deserialize your JSON, set the Binder in the JsonSerializerSettings like so:

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, Binder = new NamespaceMappingSerializationBinder { FromNamespace = "From Namespace", ToNamespace = "Your Namespace" } };

The type name parsing in the above is extremely crude. I found a much smarter parser here: How to parse C# generic type names?. You might also need to extend the custom Binder to have a dictionary of mappings.

Similarly, if you need to remap the namespace names on serialization, and are working in .Net 4.0 or above, you can override BindToName.



来源:https://stackoverflow.com/questions/28124179/handling-name-space-changes-during-deserialization-of-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!