如何从 JSON 字符串自动生成 C# 类文件 [英] How to auto-generate a C# class file from a JSON string

查看:34
本文介绍了如何从 JSON 字符串自动生成 C# 类文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下 JSON 对象,

Given the following JSON object,

form = {
  "name": "",
  "address": {
    "street": "",
    "city": "",
    "province": "",
    "postalCode": "",
    "country": ""
  },
  "phoneDay": "",
  "phoneCell": "",
  "businessName": "",
  "website": "",
  "email": ""
}

自动生成以下 C# 类的工具是什么?

what is a tool to auto-generate the following C# class?

public class ContactInfo
{
    public string Name { get; set; }
    public Address Address { get; set; }
    public string PhoneDay { get; set; }
    public string PhoneCell { get; set; }
    public string BusinessName { get; set; }
    public string Website { get; set; }
    public string Email { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string Province { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
}

我们已经看过这些问题:

We have already looked at these questions:

从 JSON Schema 生成 C# 类 询问 JSON Schemas这可能是一种在路上使用的方法.

Generate C# classes from JSON Schema Is asking about JSON Schemas which may be an approach to use down the road.

生成的 C# 类的优缺点用于 Json 对象

推荐答案

五个选项:

  • 使用免费的 jsonutils 网络工具,无需安装任何东西.

  • Use the free jsonutils web tool without installing anything.

如果您在 Visual Studio 中有 Web Essentials,请使用编辑 >粘贴专用 >将 JSON 粘贴为类.

If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.

使用免费的jsonclassgenerator.exe

网络工具 app.quicktype.io 没有需要安装任何东西.

The web tool app.quicktype.io does not require installing anything.

网络工具 json2csharp 也不需要安装任何东西.

The web tool json2csharp also does not require installing anything.

优点和缺点:

  • jsonclassgenerator converts to PascalCase but the others do not.

app.quicktype.io 有一些逻辑可以识别字典并处理名称为无效 c# 标识符的 JSON 属性.

app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.

这篇关于如何从 JSON 字符串自动生成 C# 类文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆