gpt4 book ai didi

c# - newtonsoft.json 反序列化逻辑

转载 作者:行者123 更新时间:2023-11-30 19:57:24 25 4
gpt4 key购买 nike

我正在尝试在反序列化过程中将带有例如 [1,2,3] 的 json 字符串解析为数组。

这是我的 json 数据:

[
{
"id": "1",
"district": "1",
"lon": "4.420650000000000000",
"lat": "51.21782000000000000",
"bikes": "19",
"slots": "14",
"zip": "2018",
"address": "Koningin Astridplein",
"addressNumber": null,
"nearbyStations": "3,4,5,24",
"status": "OPN",
"name": "001- Centraal Station - Astrid"
}
]

这是我的 C# 当前映射到一个常规字符串,我希望它是一个整数数组。

var AvailabilityMap = new[] { new Station() };
var data = JsonConvert.DeserializeAnonymousType(json, AvailabilityMap);

public class Station
{
public int Id { get; set; }
public double Lon { get; set; }
public double Lat { get; set; }
public int Bikes { get; set; }
public int Slots { get; set; }
public string Address { get; set; }
public string NearbyStations { get; set; }
public string Status { get; set; }
public string Name { get; set; }
}

到目前为止,我还没有找到正确的方法来执行此操作,而无需再次遍历我当前的数组..

最佳答案

创建自定义转换器。像这样:

public class StringToIntEnumerable : JsonConverter
{

public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}

public override bool CanWrite
{
get
{
return false; // we'll stick to read-only. If you want to be able
// to write it isn't that much harder to do.
}
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Note: I've skipped over a lot of error checking and trapping here
// but you might want to add some
var str = reader.Value.ToString();
return str.Split(',').Select(s => int.Parse(s));
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

现在更改类以使用 JsonConverterAttribute 来使用转换器:

public class Station
{
public int Id { get; set; }
public double Lon { get; set; }
public double Lat { get; set; }
public int Bikes { get; set; }
public int Slots { get; set; }
public string Address { get; set; }
[JsonConverter(typeof(StringToIntEnumerable))]
public IEnumerable<int> NearbyStations { get; set; } // or List<int> or int[] if
// you prefer, just make
// sure the convert returns
// the same type
public string Status { get; set; }
public string Name { get; set; }
}

现在反序列化:

var stations = JsonConvert.DeserializeObject<List<Station>>(json);

关于c# - newtonsoft.json 反序列化逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30200564/

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