【问题标题】:C# Web Api GET POST json as custom string typeC# Web Api GET POST json 作为自定义字符串类型
【发布时间】:2017-07-23 14:01:31
【问题描述】:

通过PutGet 请求,我收到了一个应该包含json 字符串的字段的空字符串。

例如: 我把下面的Json:

{
  "card": {
    "foo": "bar",
    "xyz": "dby"
  }
}

现在如果接收类有一个JObject类型的成员,那么它就被正确映射了

public class contact {
     public int id { get; set; }
     public string name { get; set; }
     public JObject card { get; set; }
}

但是,如果我将类型更改为可以接收所有 JToken 的自定义字符串类型:

public class contact {
      public int id { get; set; }
      public string name { get; set; }
      public JsonString card { get; set; } //**Changed HERE**//
    }

然后,Put 和 Get 方法都显示空字符串。

JsonString 如下所示:

public class JsonString
{
        private string _json;

        public JsonString (string json)
        {
            this._json = json;
        }

        public string Value()
        {
            return _json;
        }

        public override int GetHashCode()
        {
            return _json.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return (obj is JsonString) && this.GetHashCode() == obj.GetHashCode();
        }
        public override string ToString()
        {
                return _json;
        }
}

jsonString 类更多,但在这种情况下可能不需要。知道为什么 put/Get 会返回空字符串,我该如何解决?

编辑:

看跌期权看起来像这样:

[HttpPut]
 [Route("contacts/{contactid}")]
 public HttpResponseMessage update(int id, contact c) {
 contact.update(c);
}

【问题讨论】:

  • 这并不是对您的问题的真正回应,但如果您有时间看一下 Newtonsoft.Json,它很容易使用,并为您提供正确的序列化和反序列化到 json 和向后的对象。
  • 您到底想在JsonString 中做什么?

标签: c# json string asp.net-web-api put


【解决方案1】:

JObject 看起来像这样:

public class JObject : JContainer, IDictionary<string, JToken>, 
ICollection<KeyValuePair<string, JToken>>, IEnumerable<KeyValuePair<string, JToken>>, 
IEnumerable, INotifyPropertyChanged, ICustomTypeDescriptor, INotifyPropertyChanging

你得到的只是一个字符串,而 JObject 充当键值数据结构。

你不能像这样映射它。 动态对象可能会更好,但它仍然不是那么简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2022-06-30
    • 2011-02-20
    • 2020-03-17
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多