Custom Json Serialization of class

后端 未结 2 1241
囚心锁ツ
囚心锁ツ 2020-12-01 14:22

I have code structured like below.

public class Stats
{
        public string URL { get; set; }
        public string Status { get; set; }
        public str         


        
2条回答
  •  执念已碎
    2020-12-01 14:32

    Oh got it, re-reading your question I think you can serialize a projection of your data.

    You can try the following:

    var json = JsonConvert.SerializeObject(new { u.TotalPagesFound, u.TotalTitleTags, u.NoDuplicateTitleTags, u.NoOverlengthTitleTags } );
    

    This will convert to JSON only the int properties of your class. This is the easiest way, and it is tied to the structure of your class. If you want something more general, you will need to implement a custom converter.

    Original answer:

    I see no problem with your classes, you don't have anything weird like loop references, so Json.NET should have no problem serializing your class. So go grab Json.NET and then you can attempt the following

    // create new instance of your url stat class
    var u = new UrlStats() { URL = "a.com", TotalPages = new List() { new Stats() { URL = "b.com", Status = "xxxx" } } };
    // seralize!
    var json = JsonConvert.SerializeObject(u);
    Console.Write(json);
    

    What I get with this method is something like this:

    {"URL":"a.com","TotalPagesFound":0,"TotalPages":[{"URL":"b.com","Status":"xxxx","Title":null,"Description":null,"Length":0}],"TotalTitleTags":0,"TotalTitles":null,"NoDuplicateTitleTags":0,"DuplicateTitles":null,"NoOverlengthTitleTags":0,"OverlengthTitles":null}
    

    And that looks like good json to me.

提交回复
热议问题