복붙노트

[REDIS] JSON 문자열의 직렬화 복원시 이름 공간 변경 처리

REDIS

JSON 문자열의 직렬화 복원시 이름 공간 변경 처리

나는 레디 스 서버의 도움으로 서로의 사이에 통신하는 두 응용 프로그램을, 내 첫 번째 응용 프로그램에서 나는 다음과 같은 유형의 직렬화와 드 직렬화와 객체 수 있어요

   {
 "$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 -投矿物油和橡胶、抗氧剂,升温"
 }
 }

나는 하나의 응용 프로그램에서 수 직렬화이와 드 직렬화이하지만 난 분명히 다른 이름 공간이 다른 응용 프로그램에서 드 직렬화에이를 때. 그리고 난 예외가

JSON 'System.Collections.Generic.Dictionary`2 [mscorlib에 [선택 System.Int32, [OPCMessagingService.Resource, OPCMessagingService], mscorlib에'에서 지정된 오류 해결 형. 경로 '$ 유형', 1 호선, 위치 (138).

나는 다른 응용 프로그램에서 JSON 문자열을 직렬화 드는 내가 드 직렬화이 개체에 할 수있는 다른 무엇을 작동하지 않는 상태에서 다음을 수행하기 위해 노력했다

 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);
    }

그 밖의 무엇 나는이를 달성 할 수 있습니다.?

해결법

  1. ==============================

    1.은 "$ 유형"의 형식은 공식적으로 송신 시스템의 CLR 네임 스페이스를 포함하는 하드 코딩되어있다. 그래서, 당신은 다음 중 하나를 수행 할 수 있습니다

    은 "$ 유형"의 형식은 공식적으로 송신 시스템의 CLR 네임 스페이스를 포함하는 하드 코딩되어있다. 그래서, 당신은 다음 중 하나를 수행 할 수 있습니다

    다음은이 일에 첫 번째 컷 :

    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;
        }
    }
    

    당신이 당신의 JSON 직렬화 할 때 다음, 그래서 같은 JsonSerializerSettings에 바인더를 설정합니다 :

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

    위의 구문 분석 유형 이름은 매우 원유이다. 나는 여기에 훨씬 똑똑 파서를 발견 : 어떻게 C #을 일반적인 유형 이름을 구문 분석? 또한 매핑의 사전을 가지고 사용자 정의 바인더를 확장해야 할 수도 있습니다.

    직렬화에 네임 스페이스 이름을 매핑해야하고, 닷넷 4.0 또는 이상 작업하는 경우 마찬가지로, 당신은 BindToName을 대체 할 수 있습니다.

  2. from https://stackoverflow.com/questions/28124179/handling-name-space-changes-during-deserialization-of-json-string by cc-by-sa and MIT license