简体   繁体   English

如何将动态 JSON 转换为 C# object

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

I am trying to convert below JSON object to C# class.我正在尝试将 JSON object 以下转换为 C# ZA2F2ED4F8EBC2CBB4C21A29DC40AB61Z。 I could able to get C# equivalent for filter , but not for sort .我可以获得等效于filter的 C# ,但不适用于sort

In the case of filter JSON object;过滤器JSON object 的情况下; andOr, openCondition, etc are static.或者,openCondition等是static。 Hence, I could able to generate C# class.因此,我可以生成 C# class。

But for sort JSON object;但是对于排序JSON object; accountName , and tradeDate are not static. accountNametradeDate不是 static。 These fields are completely as per user requirement.这些字段完全按照用户要求。 They may change as some other fields for some other input.它们可能会随着某些其他输入的某些其他字段而更改。 Hence, I'm not understanding how can I generate C# class for this sort JSON object.因此,我不明白如何为这种类型的 JSON ZA8CFDE6331BD49EB2AC96F89111 Can anyone please suggest me how to do this?谁能建议我如何做到这一点?

{
    "filter": [
        {
            "andOr": "",
            "openCondition": false,
            "columnName": "accountName",
            "operator": "eq",
            "value": "KATHERINE",
            "closeCondition": false
        }
    ],
    "sort": {
            "accountName": "asc",
            "tradeDate": "desc"       
    },
    "pageIndex": 1,
    "pageSize": 75
}

I have tried to create SortCriteria class like below.我尝试创建如下所示的SortCriteria class。 But, it is not matching to the JSON sort object.但是,它与 JSON 排序 object 不匹配。

public class SortCriteria
{
    public string ColumnName { get; set; }
    public string SortOrder { get; set; }
}

Can anyone please suggest me how can I solve this issue.谁能建议我如何解决这个问题。

You could use a Dictionary (with JsonExtensionDataAttribute ) for cases where properties are NOT fixed, such as in Sort .对于属性不固定的情况,例如在Sort中,您可以使用Dictionary (使用JsonExtensionDataAttribute )。 For example,例如,

public class Filter
{
    public string andOr { get; set; }
    public bool openCondition { get; set; }
    public string columnName { get; set; }
    public string @operator { get; set; }
    public string value { get; set; }
    public bool closeCondition { get; set; }
}

public class Sort
{
    [JsonExtensionData]
    public Dictionary<string,object> RandomKeyValuePair {get;set;}
}

public class RootObject
{
    public List<Filter> filter { get; set; }
    public Sort sort { get; set; }
    public int pageIndex { get; set; }
    public int pageSize { get; set; }
}

Sample Output样品 Output

在此处输入图像描述

If your json properties are not fixed and it may change over the time then instead of creating a separate class you can use dynamic .如果您的 json 属性不固定并且它可能会随着时间的推移而改变,那么您可以使用dynamic代替创建单独的 class 。

Like,喜欢,

string jsonString = @"{
    sort: {
      accountName: 'asc',
      tradeDate: 'desc'       
    }
}";


JObject obj = JObject.Parse(jsonString);
Console.WriteLine($"AccountNumber: {obj["sort"]["accountName"]}");

using Json path,使用 Json 路径,

Console.WriteLine($"AccountNumber: {obj.SelectToken("$.sort.accountName")}");

.Net Fiddle .Net 小提琴

You can deserialize any JSON object into a Dictionary<string,object> or if you know the value type you can use that value type instead of object .您可以将任何 JSON object 反序列化为Dictionary<string,object>或者如果您知道值类型,则可以使用该值类型而不是object

In this case the sort value will only be "asc" or "desc" so we can use a string or (better) an enum在这种情况下,排序值只会是"asc""desc" ,因此我们可以使用string或(更好) enum

public enum SortDirection
{
    Asc,
    Desc,
}

The class would look like class 看起来像

public class Data
{
    ...
    [JsonProperty( "sort" )]
    public Dictionary<string,SortDirection> Sort { get; set; }
    ...
}

a minimal example一个最小的例子

var json = "{\"sort\":{\"accountName\":\"asc\",\"tradeDate\":\"desc\"}}";
var obj = JsonConvert.DeserializeObject<Data>(json);

.net fiddle example .net 小提琴示例

如何转换列表<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.

相关问题 如何将动态对象转换为JSON字符串C#? - How to convert a dynamic object to JSON string c#? 如何将C#对象转换为JSON对象 - How to convert c# object to json object 如何将 JSON 响应对象(具有动态对象)转换为 C# 类或可用的结果对象 - How to convert JSON response object (having dynamic objects) into C# classes or usable result object C#Json将任何动态对象转换为键值对 - C# Json Convert any dynamic object to key value pairs 如何在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# 如何使用C#将JSON转换为对象 - How to convert JSON to object with C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM