生成具有多个同名节点的JSON

时间:2019-06-26 01:34:06

标签: c# .net json json.net

我需要在c#中创建对象,并将其转换为以下JSON:

{
    "Order": {
        "CustomerCode": "9999999",
        "Note": "New Order for Test -- UNIT TEST",
        "Stops": {
            "Stop": {
                "Sequence": "1",
                "StopType": "P",
                "Name": "CVS"
            },
            "Stop": {
                "OrderStopID": "5",
                "Sequence": "2",
                "StopType": "D",
            }           
        },
        "Jobs": {
            "Job": {
                "Sequence": "1",
                "Drivers": {
                    "Driver": {
                        "Sequence": "1",
                        "DriverCode": "09"
                    },
                    "Driver": {
                        "Sequence": "2"
                    }
                }
            }
        }
    }
}

这是我创建的代表此的对象:

public class RootObject
{
    public Order Order { get; set; }
}


public class Order
{
    public string CustomerCode { get; set; }
    public List<Stop> Stops { get; set; }
    public List<Job> Jobs { get; set; }
}

当我使用JSON.NET序列化根对象时,我得到以下信息:

通知Stops和Jobs是作为数组生成的,我如何制作它以便在开始显示JSON时生成它?

   {
      "Order": {
        "CustomerCode": "9999999",
        "Stops": [
          {
            "Sequence": "1",
            "StopType": "P",
            "Name": "CVS"
          },
          {
            "OrderStopID": "5",
            "Sequence": "2",
            "StopType": "D",
          }
        ],
        "Jobs": [
          {
            "Sequence": "1",
            "Drivers": [
              {
                "Sequence": "1",
                "DriverCode": "09"
              },
              {
                "Sequence": "2"
              }
            ]
          }
        ]
      }
   }

1 个答案:

答案 0 :(得分:7)

您可以为此使用JsonConverter

public class ArrayConverter : JsonConverter
{
    private readonly string _propertyName;

    public ArrayConverter(string propertyName)
    {
        this._propertyName = propertyName;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(List<>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return null;
        }

        IList items = (IList)Activator.CreateInstance(objectType);
        var modelType = objectType.IsArray ? objectType.GetElementType() : objectType.GetGenericArguments().Single();

        if (reader.TokenType != JsonToken.StartObject)
        {
            throw new ArgumentOutOfRangeException(nameof(reader), "Expected object.");
        }

        while (reader.Read() && reader.TokenType != JsonToken.EndObject)
        {
            reader.Read();
            items.Add(serializer.Deserialize(reader, modelType));
        }

        return items;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is IEnumerable enumerableValue)
        {
            JObject obj = new JObject();
            writer.WriteStartObject();
            foreach (var val in enumerableValue)
            {
                writer.WritePropertyName(_propertyName);
                serializer.Serialize(writer, val);
            }
            writer.WriteEndObject();
        }
        else
        {
            throw new ArgumentOutOfRangeException(nameof(value), "Value does not implement IEnumerable.");
        }
    }
}

Try it online