윈도우 앱개발을 향하여

블로그 이미지
윈도우 10 스토어에 앱을 개발해 올리는 것을 목표로 하고 있습니다. 비전공자가 독학으로 시도하는 일이어서 얼마나 걸릴지 모르겠지만... 아무튼 목표는 그렇습니다!!
by 코딩하는 경제학도
  • Total hit
  • Today hit
  • Yesterday hit

Copyright

이 모든 내용은 Pluralsight에 Xavier Morera가 올린 'Getting Started with JSON in C# Using Json.NET'라는 강의의 네번째 챕터를 듣고 정리한 것입니다(https://app.pluralsight.com/library/courses/json-csharp-jsondotnet-getting-started/table-of-contents).


Content

Serialization Fundamentals

Settings & Attributes

Custom Serialization

Performance Tips

LINQ to JSON

JSON & XML

Binary JSON (BSON)

Json.NET Schema


Outline

Conditional Serialization

Custom JsonConverter

Callbacks

ITraceWriter for logging and debugging



Conditional Serialization

Conditional serialization may not be the case that you want to serialize an object as is, but instead only serialize based on specific conditions and this is what conditional serialization is for.


You can specify conditions in your code using ShouldSerialize which works by creating a function with a bool return type that has the name ShouldSerialize and the property name.


public class AuthorSS

{

public string Name { get; set; }

public bool IsActive { get; set; }

public string[] Courses { get; set; }

public bool ShouldSerializeCourses()

{

//If Author IsActive then Courses will be serialized

return IsActive;

}

}


target class(AuthorSS) to serialize has to have boolean member(IsActive) with bool ShouldSerialize"TargetMemberName"() method

Before Serializing the class, If IsActive set to true. then target member will be serialized. if not target member is not serialized.


Or you can use IContractResolver

The IContractResolver is very useful when you use classes that you have not defined or you do not want to add the ShouldSerialize methods to those classes, or if it's a third party code you can't modify the code or you decide you prefer to avoid placing attributes. 


public class SelectiveContractResolver : DefaultContractResolver

{

private IList<string> propertiesList = null;


public SelectiveContractResolver(IList<string> propertiesToSerialize)

{

propertiesList = propertiesToSerialize; //Get strings of property names which want to serialize

}


protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)

{

IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

return properties.Where(p => propertiesList.Contains(p.PropertyName)).ToList();

}

}


...

var contractResolver = new SelectiveContractResolver(propertiesToSerialize); //propertiesToSerialize is list of property name

string jsonstring = JsonConvert.SerializeObject(author, new JsonSerializerSettings

{

Formatting = Formatting.Indented,

ContractResolver = contractResolver

});



Custom JsonConverter

Json.NET provides JsonConvert as an easy to use wrapper over the JsonSerializer class to allow quick and easy conversion between .NET and JSON text. however, it may be possible that you want to extend or customize the serialization and deserialization process with a custom JSON converter based on the JsonConvert to fit exactly to your needs by overriding methods as required.


The JsonConverter class is the class responsible of converting from an object to JSON text and vice versa. It is extremely useful and easy to use, but what happens if you want to have finer control over the serialization and deserialization process? Well, you can create your own CustomJsonConverter class.


1. Create your own converter

2. Derived from JsonConvert

3. Override methods as needed

4. Set JsonSerializerSettings.Converters as a List<JsonConverter> with own custom converter



Callbacks

Serialization callbacks are methods that are raised before and after the serialization and deserialization process. They let you manipulate the objects or perform any operation before and after. A good example for using serialization callbacks is if you want it to have a functionality that logs the serialization time. The methods are OnSerializing and OnDeserializing, which are called before the conversion takes placed and OnSerialized and OnDeserialized which are called when the process completes.


public class Author

{

private Stopwatch timer = new Stopwatch();


public int age;

public string name { get; set; }

...


[OnSerializing]

internal void OnSerializingMethod(StreamingContext context)

{

timer.Reset(); timer.Start();

}


[OnSerialized]

internal void OnSerializedMethod(StreamingContext context)

{

timer.Stop();

}


[OnDeserializing]

internal void OnDeserializingMethod(StreamingContext context)

{

timer.Reset(); timer.Start();

}


[OnDeserialized]

internal void OnDeserializedMethod(StreamingContext context)

{

timer.Stop();

}

}



Logging and Debugging with ITraceWriter (Skip)

Debugging the serializer is not a common scenario, as in most cases everything just works, but what if you wanted to debug or if you want to understand exactly the serialization process, or you're running into an error and can't figure out what is the cause? Then you need the ITraceWriter. ITraceWriter is the method used for debugging the serialization process. Json.NET comes with a MemoryTraceWriter which logs all debugging information in memory. It's quick and easy to use or you can create your own custom TraceWriter.



출처

이 모든 내용은 Pluralsight에 Xavier Morera가 올린 'Getting Started with JSON in C# Using Json.NET'라는 강의의 네번째 챕터를 듣고 정리한 것입니다(https://app.pluralsight.com/library/courses/json-csharp-jsondotnet-getting-started/table-of-contents). 제가 정리한 것보다 더 많은 내용과 Demo를 포함하고 있으며 최종 Summary는 생략하겠습니다. Microsoft 지원을 통해 한달간 무료로 Pluralsight의 강의를 들으실 수도 있습니다.

'Programming > etc' 카테고리의 다른 글

(Json.NET) Performance Tips  (0) 2018.03.30
(Json.NET) Settings & Attributes  (0) 2018.03.30
(Json.NET) Serialization Fundamentals  (0) 2018.03.30
AND

ARTICLE CATEGORY

분류 전체보기 (56)
Programming (45)
MSDN (4)
개발노트 (2)
reference (5)

RECENT ARTICLE

RECENT COMMENT

CALENDAR

«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

ARCHIVE