简体   繁体   English

如何将任何 JSON object 转换为 C# object

[英]How to convert any JSON object to C# object

I have few different JSON objects.我有几个不同的 JSON 对象。

Fist JSON object拳头JSON object

{
    "api": {
    "NAME":"CUSTOMER_CREATE",
    "QUERY":"CUSTOMER_CREATE"
 },
 "header" : {
    "PartyNumber": "1488002",
    "OrganizationName": "Test Organization-02",
    "RawPhoneNumber": "9199199199",
    "PartyUsageCode": "EXTERNAL_LEGAL_ENTITY",
    "Address": [
{
    "AddressType": "BILL_TO",
    "Address1": "77 College Rd",
    "Address2": "London NW10 5SE",
    "Address3": "London NW10 5SF",
    "Address4": "London NW10 5SG",
    "City": "London",
    "Country": "GB",
    "PostalCode": "NW10 5ES"
}

Second JSON object第二 JSON object

 "api": {
        "NAME":"ITEM_CREATE",
        "QUERY":"ITEM_CREATE"
     },
"header" : 
{
"OrganizationCode": "IM_MASTER_ORG",
"ItemClass" : "Root Item Class",
"ItemNumber" : "TEST-01",
"ItemDescription" : "TEST-01",
"ItemStatusValue" : "Active",
"PrimaryUOMValue" : "Each",
"LifecyclePhaseValue" : "Production"
}

Also I have many JSON objects like this.我也有很多像这样的 JSON 对象。 All JSON object are not same.所有 JSON object 都不相同。 So I want to write One C# class for convert this any JSON object to C# Object. So I want to write One C# class for convert this any JSON object to C# Object. So can you please me one class to convert these JSON object.所以你能请我一个 class 来转换这些 JSON object。

Currently I am using this class to convert Json object.目前我正在使用这个 class 来转换 Json object。 but I want to make this as a dynamic class但我想把它做成动态的 class

public class MHScaleMessage {

    //public string api { get; set;}
    public Dictionary<string, string> api { get; set;}  = new Dictionary<string, string>();
    public Dictionary<string, string> header {get; set; }  = new Dictionary<string, string>();                 
    public List<Dictionary<string, string>> lineItems { get; set; } = new List<Dictionary<string, string>>();

    public static string GetValue(Dictionary<string, string> d, string key, string defaultVal="") {
        if (key == null) return defaultVal;
        return d.TryGetValue(key, out string val) ? val : defaultVal;
    }

    public static int GetValueAsInt(Dictionary<string, string> d, string key, int defaultVal=0) {
        if (key == null) return defaultVal;
        string val = d.TryGetValue(key, out val) ? val : null;
        if (val == null) return defaultVal;
        return int.TryParse(val, out _) ? 0 : defaultVal;
    }

    public string ToJsonString() {
        var options = new JsonSerializerOptions
        {
            WriteIndented = true,
            IgnoreNullValues = true
        };
        return System.Text.Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(this, options));
    }
    
    public  string _ToString() {
        string s="";
        s += "{"; s += "\n";
        s += "api = " + api; s += ","; s += "\n";
        s += "header ="; s += "\n";
        s += "{";
        header.ToList().ForEach(x => s += x.Key + " = " + x.Value + "\n");
        s += "}"; s += ","; s += "\n";
        s += "lineItems"; s += "\n";
        s += "{"; s += "[";
        lineItems.ForEach(x => {
            x.ToList().ForEach(y => {
                s += y.Key + " = " + y.Value; 
                s += ","; s += "\n";
            }
            );
        });
        s += "]";  s += "}"; s += "\n";
        s += "}";
        return s;
    }       
}

After that I am using following method to perform API.之后,我使用以下方法执行 API。 to this method I can pass parameter.这个方法我可以传递参数。

  private static MHScaleMessage PerformAPIFunction(MHScaleMessage requestObj)
    {}

There are multiple ways to convert a JSON object to a C# sharp object and here I am going to show a few ways.有多种方法可以将 JSON object 转换为 C# 尖锐的 ZA8CFDE6331BD59EB2AC96F8911ZC46 方法,我将在这里展示几种方法。

One Line Code一行代码

var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);

If you have your own class then change var to your own class.如果您有自己的 class,则将var更改为您自己的 class。

Use JSON.NET使用JSON.NET

There is a recommended way to convert JSON to C# object and that is JSON.NET Have a look at the github repo to get more information. There is a recommended way to convert JSON to C# object and that is JSON.NET Have a look at the github repo to get more information. Here is an example for your case.这是您的案例的示例。

public class User
{
public User(string json)
{
    JObject jObject = JObject.Parse(json);
    JToken jUser = jObject["api"];
    name = (string) jUser["NAME"];
    query = (string) jUser["QUERY"];
    JToken jUser1 = jObject["header"];
    OrganizationCode = (string) jUser1["OrganizationCode"];
    ItemClass = (string) jUser1["ItemClass"];
    ItemNumber = jUser1["ItemNumber"];
}

public string api_Name{ get; set; }
public string api_Query { get; set; }
public string header_OrganizationCode{ get; set; }
public string header_ItemClass{ get; set; }
}

// Use
private void Run()
{
string json = @"{""user"": 
{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
User user = new User(json);

Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");

foreach (var player in user.players)
    Console.WriteLine(player);
}

You can get your requirement easily by using Newtonsoft.Json library.您可以使用 Newtonsoft.Json 库轻松满足您的要求。 I am writing down the one example below have a look into it.我正在写下下面的一个例子,看看它。

Class for the type of object you receive: Class 对于您收到的 object 类型:

public class Student
 {
   public int ID { get; set; }
   public string Name { get; set; }
 }

Code:代码:

static void Main(string[] args)
 {
   string json = "{\"ID\": 1, \"Name\": \"Abdullah\"}";
   Student student = JsonConvert.DeserializeObject<User>(json);

   Console.ReadKey();
 }

Simple way to parse your json.解析 json 的简单方法。

如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C#

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 c# - 如何在没有任何模型或映射器的情况下将json转换为对象 - How to convert json to object without any model or mapper in c# 如何将C#对象转换为JSON对象 - How to convert c# object to json object 如何使用C#将JSON转换为对象 - How to convert JSON to object with C# 如何在C#中将json数据转换为对象? - How to convert json data to object in C#? 如何将 Json 转换为 C# object? - How to convert Json into C# object? 如何在C#中将json字符串转换为对象 - how to convert json string to object in C# 如何将此json转换为C#对象 - How to convert this json into C# object 如何在C#中将Json对象转换为数组 - How to Convert Json Object to Array in C# 如何将这个JSON到C#对象转换 - How to convert this JSON to C# object 如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM