gpt4 book ai didi

c# - 将嵌套在动态对象中的 C# 列表中的第一项和最后一项序列化为 JSON

转载 作者:行者123 更新时间:2023-12-04 10:26:56 27 4
gpt4 key购买 nike

我有一个类需要将任何类型的对象序列化为 JSON。如果对象具有一个或多个列表类型的属性,我想序列化整个对象,但只序列化列表中的第一项和最后一项。

例如,我有下面的代码

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json.Serialization;
using System.Linq;
using Newtonsoft.Json.Linq;

public class Program
{
public class Product{
public Product(string name, int price){
this.Name = name;
this.Price = price;
}
public string Name {get;set;}
public int Price {get;set;}
}

public class ProductResult{
public ProductResult(List<Product> products, int code){
this.Products = products;
this.Code = code;
}
public int Code {get;set;}
public List<Product> Products {get;set;}
}

public static string DoTheThing(object dynamicObject){
return JsonConvert.SerializeObject(dynamicObject);
}

public static void Main()
{
var list = new List<Product>(){new Product("product1",100),new Product("product2",100),new Product("product3",100),new Product("product4",100)};
var result = new ProductResult(list,0);

string jsonObj = DoTheThing(result);
Console.WriteLine(jsonObj);
// Output {"Code":0,"Products":[{"Name":"product1","Price":100},{"Name":"product2","Price":100},{"Name":"product3","Price":100},{"Name":"product4","Price":100}]}
}
}

我希望它输出以下内容,我需要它能够处理各种对象类型。

{"Code":0,"Products":[{"Name":"product","Price":100},{"Name":"product","Price":100}]}

我看了一下使用 Custom JsonConverterCustom ContractResolver但我不确定如何实现这些。

最佳答案

您可以使用自定义的 JsonConverter 来完成此操作,例如:

public class FirstAndLastListConverter : JsonConverter
{
// We only care about List<> properties
public override bool CanConvert(Type objectType) =>
objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(List<>);

// We are not deserialising, complete this if you really need to, but I don't see why you would
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Convert the value to an IList
var elements = value as IList;

// Start a new array
writer.WriteStartArray();

// Serialise the first item
serializer.Serialize(writer, elements[0]);

// Serialise the last item
serializer.Serialize(writer, elements[elements.Count - 1]);

// End the array
writer.WriteEndArray();
}
}

然后像这样使用它:

// A settings object to use our new converter
var settings = new JsonSerializerSettings
{
Converters = new [] { new FirstAndLastListConverter() }
};

// Use the settings when serialising
var json = JsonConvert.SerializeObject(result, settings);

关于c# - 将嵌套在动态对象中的 C# 列表中的第一项和最后一项序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60601612/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com