. NET Platform Open source Project Quick Glance C # Platform JSON entity class Builder JSON C # class Generator

Source: Internet
Author: User

Last year, I was in an article using the original method to parse complex strings, JSON must use Jsonmapper? Describes the simple JSON parsing problem, which is very convenient in the environment, because there is no need to generate entity classes, the structure is easy to parse. But with the business changes, will also encounter the super-perverted JSON, if also in accordance with the previous ideas, will make people out of convulsions, once the structure changes, and again. So today we are going to introduce you to an easy way to get rid of the super-perverted JSON, although you need to generate entity classes. It is open Source: The JSON C # Class Generator component.

. NET Open Source directory: "Directory" of this blog other. NET open source project articles Directory

This text address: http://www.cnblogs.com/asxinyu/p/dotnet_Opensource_project_json_generator.html

1. What does a complex JSON look like?

Look at the following figure, the text files are 12K, nested multi-layered, to tell the truth, I am not patient to see down. So I found a tool to structure a bit. See chart comparison:

2. Using JSON C # Class generator to introduce and use

The JSON C # Class Generator is an application that generates C # from JSON text. Project address: https://jsonclassgenerator.codeplex.com/, currently supports arrays, objects, shaping, single-precision, Boolean, string, and null-value character types.

The process is simple, as shown in the official website: Enter the namespace, the main class name, the generated CS file directory, and the type. At the same time, the right side has visibility, and some simple configuration, easy to understand.

  

Let's take a look at the JSON that we're demonstrating, a demo of JSON code found on the Web, and some of the actual data I'm using is somewhat more complicated than that. First we copy the JSON into the JSON C # Class generator, set the relevant parameters, as shown, after the file is generated, copied to the project, we can write the test code, look at the parsed format:

To illustrate, we need to use the Newtonsoft component for JSON deserialization, which I believe most certainly is more familiar than I am. Copy the resulting file into the project and add a reference to the following code to deserialize OK. Isn't so easy?

Get jsonzifc var json = File.readalltext ("complex JSON example. txt");//use Newtonsoft to deserialize var model = Jsonconvert.deserializeobject <TestJson> (JSON);

In fact, most people understand this routine, but I know there are some online parsing tools, but it seems to encounter particularly complex, not the whole, this tool is I have seen the inside relatively easy to use. Look at the parsed data, structured, very clear, I want that data, go to the property in turn to get it.

3. So it's over? No, it's not that simple.

Tools can solve the problem is generally not all, can solve 80% is very good, although this tool has just begun to solve a lot of problems, but with the complexity of the JSON, also met some pits, see how pits. Now it's a pits.

3.1 Why to useNested classes (nested classes)

Why in the case of complex types I choose to use nested classes, the reason is very simple, the structure is clearer, otherwise generated CS file inside a bunch of classes, do not know that is the most outside, to this demand, appropriate code redundancy does not matter, I need to quickly get the data they want. Not to mention auto-generated. Of course, for simple types, it is OK not to use nested classes, see personal habits.

3.2 Parsing will run intofields with a type name of number

Although the comparison is very wonderful, but indeed encountered, get the JSON string inside the field name is a number, how to break? Ghosts know people so spell out, anyway, is to collect, but also have to have antidote. Since the original is the number, then the original to change, we put the attribute is the number of places, all to add a default value, and then generate the entity class, do not, but want to in such a heap of things in a mess of all the numeric attributes to add a default value, it is not easy ah, fortunately there is a universal regular expression.

Let's write a simple regular expression matching method, replace the numeric attribute with a default letter A, the code is as follows:

public static string Getnewjson (String json) {Regex reg = new Regex ("\" ([^\ "]d*) \": "); Note that the quotes inside are enclosed in double quotes instead of the backslash matchevaluator matcheval = new MatchEvaluator (Replacestar) and return Reg. Replace (JSON, matcheval);} static string Replacestar (match match) {string str = match. Value.replace ("\" "," "). Replace (":", ""); return "\" A "+ str +" \ ":";}
3.3 of the same structure, but resolved to a different class name

Many times a property under the same structure of the object, but will be resolved according to the name of different classes, the basic structure has been, in the acquisition of object data, is not an array object, the loop is not good, then how to break?

Manually build an intermediate class, the same structure as they do, using Tinymaper, here an article introduced, these types are mapped to this intermediate class by default, and then all other identical structural object parsing only need to write a copy of the code is OK. Look at the following methods:

public class Linerato{public string Lgmailno;public string createtime;     public string eventtime;     public string eventaddress;     public string NodeType; public string timeout;///<summary> converts other classes of the same structure to intermediate classes </summary>public static Linerato getline<t> (T Model) {tinymapper.bind<t, linerato> (); return tinymapper.map<linerato> (model);}}
3.4 Null valueCause entity class fields to be missing

Sometimes when we first get the JSON value, because some value is empty, resulting in the actual JSON value does not include the field, so at the time of the generated entity class does not have this field, and the actual number of times found that the value is not empty, will lead to parsing failure, this time how to break?

No way to break, in order to save trouble, see where the missing field, manually add it, just a line of code things.

In short, after solving the 80% problem, the rest of the method is more than the problem, we recount it. Here's just the solution of their own writing down, the quickest solution to the problem, ok! Other things that cost brain cells are still for those who have energy!

4. Resources

This article is code: Jsonclasstest.rar

Project Address:https://jsonclassgenerator.codeplex.com/

. NET Platform Open source Project Quick Glance C # Platform JSON entity class Builder JSON C # class Generator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.