如何更简单地反序列化 json 数组?

How to deserialize a json array more simply?

有没有办法只从数据集中获取数据而忽略起始数组'result'?

{
    "result": [
        "",
        {
            "dataset": [
                {
                    "idSottogruppo": "7",
                    "Sottogruppo": "Distribuzione Ausiliaria"
                }, {
                    "idSottogruppo": "6",
                    "Sottogruppo": "Distribuzione Motore"
                }, {
                    "idSottogruppo": "8",
                    "Sottogruppo": "Filtri"
                }, {
                    "idSottogruppo": "39",
                    "Sottogruppo": "Motore"
                }
            ]
        }
    ]
}

这就是我的做法并且有效,我只是想尽可能减少代码,因为所有 API 方法都具有相同的 JSON 格式。

我的代码:

public class OE_GetActiveSubGroupsResultDTO
{
    public List<OE_GetSubActiveGroupsListDTO> Result { get; set; }
}

public class OE_GetActiveSubGroupsListDTO
{
    public List<OE_GetActiveSubGroupsDTO> Dataset { get; set; }
}

public class OE_GetActiveSubGroupsDTO
{
    public string idSottogruppo { get; set; }
    public string Sottogruppo { get; set; }
}

public ActionResult ProcessSpareParts(CarViewModel vm)
{
    OE_GetActiveItemsResultDTO activeItemsResultDeserialize = JsonConvert.DeserializeObject<OE_GetActiveItemsResultDTO>(GetActiveSubGroups);
                            
    foreach(var activeItemsResult in activeItemsResultDeserialize.Result[1].Dataset)
    {
        OE_GetActiveItemsDTO activeItems = new JavaScriptSerializer().Deserialize<OE_GetActiveItemsDTO>(activeItemsResult .ToString());    
        ...
    }
}

如果你使用JSON.NET,那么你应该将JSON文本读入JToken图形,然后遍历图形提取内部dataset - 这样你就不需要 wrapper/outer DTO 类型了。

然后您可以使用 Linq 将 JArray 中的 JObject 中的数据提取到元组列表中:

public static JArray? GetDatasetFromJson( String jsonText )
{
    JToken root = JToken.Parse( jsonText );
    
    if( root is JObject rootObj && rootObj.TryGetValue("result", out JToken? resultArr ) && resultArr is JArray ra )
    {
        if( ra.Count == 2 )
        {
            if( ra[1] is JObject datasetWrapper )
            {
                if( datasetWrapper.TryGetValue( "dataset", out JToken? datasetTok ) && datasetTok is JArray dataset )
                {
                    return dataset;
                }
            
            }
        }
    }

    return null;
}

public static List<(String id, String value)> GetDataSetItems( JArray arr )
{
    return arr
        .OfType<JObject>()
        .Select( e => ( id: e["idSottogruppo"], value: e["Sottogruppo"] ) )
        .ToList();
}

public static void Main()
{
    String jsonText = @"""result"": [ """", { ""dataset"": [ etc ]";

    JArray? dataset = GetDatasetFromJson( jsonText );

    if( dataset is null )
    {
        throw new InvalidOperationException( "Couldn't find dataset array in JSON." )
    }

    List<(String id, String value)> items = GetDataSetItems( dataset );
}

在 Linqpad 中给我这个输出:

这是一行代码

Note: this code doesn't do any validation to Input data. This code works if the format of the json doesn't change

string json = File.ReadAllText("json1.json");

var result = JObject.Parse(json)["result"][0]
                    .Next["dataset"]
                    .Select(x => new OE_GetActiveSubGroupsDTO 
                    { 
                            idSottogruppo = x["idSottogruppo"].ToString(), 
                            Sottogruppo = x["Sottogruppo"].ToString() 
                    });