0

We are having an issue getting JSON to serialize and deserialize derived classes properly. We have attempted to apply settings to a JsonConvert method, but that doesn't seem to be working.

The classes serialize and deserialize in XML just fine. This is what it looks like in XML

<Root>
   <Entities>
        <Entity xsi:type="Entity_Individual" x="1" y="2" etc...>

The Root class look like this:

[Serializable()]
[KnownType(typeof(Entity_Individual))]        
public class Root
{
  [JsonProperty]
  [XmlArray("Entities")]
  [XmlArrayItem("Entity")]
  public List<Entity> Entities { get; set; }
}

The Entity_Individual class looks like this:

public class Entity_Individual : Entity
{
    [JsonProperty]
    [XmlAttribute("x")]
    public string x{ get; set; }
}

The code is:

    JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
    HttpClient httpClient = new HttpClient();
    var content = JsonConvert.SerializeObject(root, settings);
    var bodyContent = new StringContent(content, Encoding.UTF8, "application/json");
    var url = ApiRoutes.Posts.GetURL("XXXXXXXX", 1);
    var Result = await httpClient.PostAsync(url, bodyContent);

the "content" variable has the following:

{"$type":"Root","$type":"Entities.Models.v1.Root, Entities","Entities":{"$type":"System.Collections.Generic.List`1[[Entities.Models.v1.Entity, Entities]], mscorlib","$values":[{"$type":"Entity_Individual","$type":"Entities.Models.v1.Entity_Individual, Entities","Domain":null,"isEnabled":false,"FName":null,"MName":null,"LName":null,"UserID":null,"State":null,"IPAddress":null,"Entity_Professions":null,"Entity_Roles":null,"ID":178206,"Entity_RelationshipTypeID":0,"Entity_Addresses":null,"Entity_Emails":null,"Entities":null,"Entity_DocPath":null,"Entity_Document":null,"Entity_Phones":null,"Entity_Notes":null,"Method":null,"AuditActions":null,"DateEntered":"0001-01-01T00:00:00"}]},"AuthorizedUserEntityID":0,"ActiveEntityID":0,"ActiveEntityType":null,"Contract_Documents":null,"Tables":null}

The error received is coming back from the post to our own web api:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-126bdb2427533f40ad801f024281eaca-7da99ffdf6845545-00","errors":{"$.Entities":["The JSON value could not be converted to System.Collections.Generic.List`1[Entities.Models.v1.Entity]. Path: $.Entities | LineNumber: 0 | BytePositionInLine: 90."]}}
Greg
  • 85
  • 1
  • 8
  • I might be being blind, but I couldn't see in your JSON any property named x? – Caius Jard Jan 20 '21 at 20:33
  • There isn't. "x" is a placeholder. The class has a ton of actual attributes that were truncated. The error doesn't seem to relate to the attributes, but rather the class/elements, so for simplicity sake we omitted. – Greg Jan 20 '21 at 20:36

0 Answers0