Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following class structure:

[JsonObject]
public class Polygon : IEnumerable<Point>
{
    public List<Point> Vertices { get; set; }
    public AxisAlignedRectangle Envelope { get; set; }
}

public class AxisAlignedRectangle : Polygon {
    public double Left { get; set; }
    ...
}

I am serializing the Polygon class, but when I do, I get a JsonSerializationException, with the message "Self referencing loop detected for property 'Envelope' with type 'MyNamespace.AxisAlignedRectangle'." If I add [JsonObject(IsReference = true)] (as described here) to AxisAlignedRectangle, the code runs fine, but I get an auto-assigned $id field in each instance of AxisAlignedRectangle, and a $ref field when that instance is re-referenced. For example, when I serialize a polygon, I get:

{
    Vertices: [ ... ],
    Envelope: {
        $id: '1',
        Left: -5,
        ...
        Vertices: [ ... ],
        Envelope: {
            $ref: '1'
        }
    }
}

My desire is to remove the Polygon properties entirely when I serialize an AxisAlignedRectangle. I tried adding a DataContractAttribute to the AxisAlignedRectangle class (along with appropriate DataMemberAttribute attributes), but all the properties of Polygon were still being serialized. This was unexpected, since there is an example in the Json.NET documentation that appears to indicate such an approach should work.

Does anyone know a way to explicitly remove (most importantly) the Envelope property from the resulting Json.NET serialization, when the type being serialized is AxisAlignedRectangle? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
419 views
Welcome To Ask or Share your Answers For Others

1 Answer

Most simple way to do it is simply decorate the AxisAlignedRectangle object with [JsonObject(MemberSerialization.OptIn)].

In a sentence, it will serialize only properties decorated with [JsonProperty] attribute. You can read more here: MemberSerialization Enumeration.

Another option is to decorate the Polygon properties with JsonIgnoreAttribute Class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...