Fluent-json是C#的JSON生成器和解析器,除了支持基本的JSON操作,还可以映射自定义类到JSON数据格式。这是一个线程安全的库,同时确保强类型安全。
示例代码:
JsonEncoder<Book>encoder=Json.EncoderFor<Book>(config=>config.MapType<Book>(map=>map.AllFields()//DateTimecan'tbeencodedtonativejson.Conversionisrequired..Field<DateTime>(field=>field.pubDate,pubDate=>pubDate.EncodeAs<string>(value=>value.ToShortDateString()))//BookTypecan'tbeencodedeither,let'sconvertittoo..Field<BookType>(field=>field.type,type=>type.EncodeAs<int>(value=>(int)value)//Letsassumewewouldwanttoencodethisfieldtoa//differentjsonfield..To("book_type"))).MapType<Author>(map=>map.AllFields()).UseTidy(true));Bookbook=newBook();book.title="Aroundtheworldin80days";book.tags=newList<string>{"traveling","adventure"};book.pageCount=342;book.pubDate=DateTime.Now;book.author=newAuthor();book.author.forname="Jules";book.author.surname="Verne";stringjson=encoder.Encode(book);
评论