简体   繁体   中英

C# Web Api GET POST json as custom string type

With Put and Get request I receive empty strings for a field that should contain json string.

For example: I Put the following Json:

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

Now if the receiving class has a member of type JObject, then it is mapped correctly

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

However if I change the type to a custom string type that can receive all JTokens:

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

Then, the Put and Get method both show empty strings.

JsonString looks like as follows:

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

The jsonString class more, but probably not needed in this context. Any idea why The put/Get are returning empty strings and how can I fix this?

EDIT:

The Put looks like this:

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

JObject looks like this:

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

What you've got is just a string, while JObject acts as a key-value datastucture.

You can't just map it like this. You might have better luck with dynamic object but still it is not that simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM