如何从字典值(对象)转型对象类

时间:2016-01-16 08:20:36

标签: c# json.net jsonfx

如何解决类型转换错误...
我想用JSON创建新的对象..

我附上了示例代码..

-(void)sendTask:(NSURLRequest*)request successCallback:(void (^)(NSDictionary*))success errorCallback:(void (^)(NSString*))errorCallback
{

   __weak __typeof(self)weakSelf = self;
    NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        [self parseResponse:response data:data fromRequest:request successCallback:success errorCallback:^(NSString *error)
        {
            //if auth token expired and getting "not authenticated" error (status 401)
            NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
            if (httpResp.statusCode == 401) {
                [self refreshAuthenticationTokenWithSuccessCallback:^(NSDictionary *response) {
                    self.authToken = response[@"token"];
                    //attempt to re-try the request that failed due to token expiration
                    [weakSelf sendTask:request successCallback:success errorCallback:errorCallback];
                } errorCallback:^(NSString *error) {
                    //two weeks have passed and the token is no longer refreshable
                    NSLog(@"TOKEN NOT REFRESHABLE! HAVE TO LOG IN MANUALLY");
                }];
            }
        }];
    }];
    [task resume];
}

1 个答案:

答案 0 :(得分:1)

你得到了字符串,人物和人物的字典,这就是它抛出异常的原因。

尝试var person = JsonConvert.DeserializeObject<Person>((dic["data"].ToString()));

而不是Person p2 = (Person)dic["data"];

person.age将是25

编辑:

  public MainWindow()
        {
            InitializeComponent();

            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("type", "Person");
            dic.Add("data", new Person(25));

            string json = JsonConvert.SerializeObject(dic);

            dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
            var person = JsonConvert.DeserializeObject<Person>((dic["data"].ToString()));

            Console.WriteLine(person.age);
        }

希望帮助!