使用JsonConvert反序列化三级JSON数据及示例解析
Got it, let's walk through how to deserialize your 3-level JSON using JsonConvert (from Newtonsoft.Json, the go-to JSON library for .NET). The core idea is to first map your JSON hierarchy to matching C# classes, then use the deserialization method to turn the raw JSON string into strongly-typed objects you can work with easily.
Step 1: Define C# Classes That Match the JSON Structure
Your JSON has three distinct nested levels—let's build classes for each:
- Root object (top-level properties like
Name,PickDate, plus thePickListsLinesarray) PickListsLinesitems (each has properties likeLineNumber,PickedQuantity, plus theDocumentLinesBinAllocationsarray)DocumentLinesBinAllocationsitems (the deepest level; I'll define a base class here—you can fill in actual fields based on your full JSON)
Here's the tailored class structure:
using Newtonsoft.Json; using System.Collections.Generic; // Root level class public class PickList { public int Absoluteentry { get; set; } public string Name { get; set; } public int OwnerCode { get; set; } public string OwnerName { get; set; } // Handles the null value in your sample public string PickDate { get; set; } public string Remarks { get; set; } public string Status { get; set; } public string ObjectType { get; set; } public string UseBaseUnits { get; set; } public List<PickListLine> PickListsLines { get; set; } } // Second level (items in PickListsLines array) public class PickListLine { public int AbsoluteEntry { get; set; } public int LineNumber { get; set; } public int OrderEntry { get; set; } public int OrderRowID { get; set; } public int PickedQuantity { get; set; } public string PickStatus { get; set; } public int ReleasedQuantity { get; set; } public int PreviouslyReleasedQuantity { get; set; } public int BaseObjectType { get; set; } public List<object> SerialNumbers { get; set; } // Empty array in sample; adjust type if needed public List<object> BatchNumbers { get; set; } // Empty array in sample; adjust type if needed public List<DocumentLineBinAllocation> DocumentLinesBinAllocations { get; set; } } // Third level (items in DocumentLinesBinAllocations array) public class DocumentLineBinAllocation { // Add your actual fields here based on the full JSON (replace the ... in your sample) // Example: // public string BinCode { get; set; } // public int AllocatedQuantity { get; set; } }
Quick Notes on Class Setup:
- If
StatusorPickStatusshould be enums instead of strings, add theStringEnumConverterattribute to handle the string-to-enum conversion:[JsonConverter(typeof(StringEnumConverter))] public PickStatus Status { get; set; } // Define an enum PickStatus with values like ps_Released - If
SerialNumbersorBatchNumbersaren't empty (they'll have actual objects later), create a matching class for them and update theListtype accordingly.
Step 2: Deserialize the JSON String
Once your classes are ready, deserialization is straightforward. Use JsonConvert.DeserializeObject<T>() where T is your root class (PickList):
// Your raw JSON string (replace with your actual full JSON) string json = @"{""Absoluteentry"": 6, ""Name"": ""ricpez"", ""OwnerCode"": 16, ""OwnerName"": null, ""PickDate"": ""2018-03-27"", ""Remarks"": """", ""Status"": ""ps_Released"", ""ObjectType"": ""156"", ""UseBaseUnits"": ""tNO"", ""PickListsLines"": [ { ""AbsoluteEntry"": 6, ""LineNumber"": 0, ""OrderEntry"": 417, ""OrderRowID"": 0, ""PickedQuantity"": 0, ""PickStatus"": ""ps_Released"", ""ReleasedQuantity"": 5, ""PreviouslyReleasedQuantity"": 5, ""BaseObjectType"": 17, ""SerialNumbers"": [], ""BatchNumbers"": [], ""DocumentLinesBinAllocations"": [] } ]}"; // Convert JSON to strongly-typed object PickList pickList = JsonConvert.DeserializeObject<PickList>(json);
Step 3: Navigate the 3-Level Data
Now you can easily access all levels of the deserialized object:
// Loop through second-level PickListsLines foreach (var line in pickList.PickListsLines) { Console.WriteLine($"Line Number: {line.LineNumber}, Released Quantity: {line.ReleasedQuantity}"); // Loop through third-level DocumentLinesBinAllocations foreach (var binAllocation in line.DocumentLinesBinAllocations) { // Access properties once you've defined them in the DocumentLineBinAllocation class // Console.WriteLine($"Bin Code: {binAllocation.BinCode}"); } }
Troubleshooting Tips
- If you get deserialization errors, check for mismatched property names (use
[JsonProperty("ExactJsonPropertyName")]if your C# property name doesn't match the JSON's case or spelling) - Mark properties as nullable (e.g.,
public string? OwnerName { get; set; }in C# 8+) if they might be missing or null - Use
JsonConvert.DeserializeObject<JObject>(json)first if you need to inspect the JSON structure dynamically before building your classes.
内容的提问来源于stack exchange,提问作者Riccardo Pezzolati

