根据类型反序列化json字符串

时间:2016-02-03 16:49:33

标签: c# json.net

有这样的json字符串(我无法控制发布者):

{
  "TypeName": "Type1"
}

{
  "TypeName": "Type1"
}

这是动态反序列化json字符串的可接受方式吗?:

public class DeserializationFactory
{
    public static IPoco GetEvent(string jsonString)
    {
        var o = JObject.Parse(jsonString);
        IPoco poco = null;
        switch (o["TypeName"].ToString())
        {
        case "Type1":
            poco = JsonConvert.DeserializeObject<Type1>(jsonString);
            break;

        case "Type2":
            poco = JsonConvert.DeserializeObject<Type2>(jsonString);
            break;
        }
        return poco;
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用DataFrame.stack转换器实现和此布局:

export class HttpInterceptor extends Http {
  public loaderService: LoaderService

  constructor(backend: ConnectionBackend,
              defaultOptions: RequestOptions,
              public events: Events) {
    super(backend, defaultOptions);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.intercept(super.get(url, options));
  }

  post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.intercept(super.post(url, body, this.getRequestOptionArgs(options)));
  }


  getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
    if (options == null) {
      options = new RequestOptions();
    }
    if (options.headers == null) {
      options.headers = new Headers();
    }

    options.headers.append('Content-Type', 'application/json');
    return options;
  }

  intercept(observable: Observable<Response>): Observable<Response> {
    this.events.publish('showLoader');
    return observable
      .catch(
        (err) => {
          if (err.status == 401) {
            this.events.publish('unAuthorizedRequest', err);
            this.events.publish('hideLoader');
            return Observable.empty();
          } else {
            this.events.publish('hideLoader');
            return Observable.throw(err);

          }
        })
      .do(
        () => {
          this.events.publish('hideLoader');
          return Observable.empty();
        },
        () => {
          this.events.publish('hideLoader');
          return Observable.empty();
        }
      );
  }
}