Home Web Front-end JS Tutorial Summary of conversion methods between .net entity classes and json

Summary of conversion methods between .net entity classes and json

Apr 25, 2018 pm 01:41 PM
.net javascript json

This time I will bring you a summary of the conversion methods between .net entity classes and json. What are the precautions for converting .net entity classes and json. The following is a practical case, let's take a look.

When converting between .net entity classes and json, pay attention to the following points:

1. References added when writing jsonhelp. System.Runtime.Serialization.Json;
2. The entity class needs to be declared as public

jsonhelp code:

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

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Runtime.Serialization.Json;

using System.IO;

namespace JsonTest

{

  class JsonHelp

  {

    public JsonHelp()

  {

    //

    // TODO: Add constructor logic here

    //

  }

  /// <summary>

  /// 把对象序列化 JSON 字符串 

  /// </summary>

  /// <typeparam name="T">对象类型</typeparam>

  /// <param name="obj">对象实体</param>

  /// <returns>JSON字符串</returns>

  public static string GetJson<T>(T obj)

  {

    //记住 添加引用 System.ServiceModel.Web 

    /**

     * 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不来的哦

     * */

    DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));

    using (MemoryStream ms = new MemoryStream())

    {

      json.WriteObject(ms, obj);

      string szJson = Encoding.UTF8.GetString(ms.ToArray());

      return szJson;

    }

  }

  /// <summary>

  /// 把JSON字符串还原为对象

  /// </summary>

  /// <typeparam name="T">对象类型</typeparam>

  /// <param name="szJson">JSON字符串</param>

  /// <returns>对象实体</returns>

  public static T ParseFormJson<T>(string szJson)

  {

    T obj = Activator.CreateInstance<T>();

    using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes(szJson)))

    {

      DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));

      return (T)dcj.ReadObject(ms);

    }

  }

  

  }

}

Copy after login

Entity class code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace JsonTest

{

 public class testData

  {

    public testData()

  {

  }

  public int Id { get; set; }

  public string Name { get; set; }

  public string Sex { get; set; }

  }

}

Copy after login

Console application test code:

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

31

32

33

34

35

36

37

38

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace JsonTest

{

  class Program

  {

    static void Main(string[] args)

    {

      //实体类转json

      testData t1 = new testData();

      t1.Id = 1;

      t1.Name = "001姓名";

      t1.Sex = "男";

      testData t2 = new testData();

      t2.Id = 2;

      t2.Name = "002姓名";

      t2.Sex = "男";

      testData t3 = new testData();

      t3.Id = 3;

      t3.Name = "003姓名";

      t3.Sex = "男";

      List<testData> tlist = new List<testData>();

      tlist.Add(t1);

      tlist.Add(t2);

      tlist.Add(t3);

     Console.WriteLine(JsonHelp.GetJson<List<testData>>(tlist));

      // Console.ReadKey();

      //json转实体类

     List<testData> tl = JsonHelp.ParseFormJson <List<testData>>(JsonHelp.GetJson<List<testData>>(tlist));

     Console.WriteLine(tl.Count);

     Console.WriteLine(tl[0].Name);

     Console.ReadKey();

    }

  }

}

Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website !

Recommended reading:

jQuery creates a vertical translucent accordion effect

jquery implements the navigation menu mouse prompt function

The above is the detailed content of Summary of conversion methods between .net entity classes and json. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

Quick tips for converting PHP arrays to JSON Quick tips for converting PHP arrays to JSON May 03, 2024 pm 06:33 PM

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

How to use PHP functions to process JSON data? How to use PHP functions to process JSON data? May 04, 2024 pm 03:21 PM

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ​​of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

PHP Tutorial: How to Convert JSON Unicode to Chinese Characters PHP Tutorial: How to Convert JSON Unicode to Chinese Characters Mar 05, 2024 pm 06:36 PM

JSON (JavaScriptObjectNotation) is a lightweight data exchange format commonly used for data exchange between web applications. When processing JSON data, we often encounter Unicode-encoded Chinese characters (such as "u4e2du6587") and need to convert them into readable Chinese characters. In PHP, we can achieve this conversion through some simple methods. Next, we will detail how to convert JSONUnico

See all articles