我有一个嵌套对象
public class CardListViewModel
{
public virtual Guid Id { get; set; }
public virtual IEnumerable<Card> CardList { get; set; }
}
public class Card
{
public virtual Guid Id { get; set; }
public virtual string IndexName { get; set; }
public virtual Image CardImage { get; set; }
}
public class Image
{
//...
public virtual string Src { get; set; }
//...
}
所以卡可能是
CardListViewModel.CardList[0] = {Id:5678, IndexName:"Visa", {Src:"Visa.png"}}
CardListViewModel.CardList[1] = {Id:5555, IndexName:"MasterCard", {Src:"MasterCard.png"}}
我想要的结果是Json对象,如下所示
{
"Visa": "Visa.png",
"MasterCard": "MasterCard.png"
}
我无法修改POCO,我想要的只是列表中每张卡的JSON片段及其相应的图像。当然,我可以使用StringBuilder
和循环来强制执行此操作,但我想知道是否有办法通过JsonConvert
库或任何其他可以为我处理映射的好工具来完成此操作?
答案 0 :(得分:2)
我使用LINQ来映射它,使用NewtonsoftJson来构建JSON。
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
var mappedCards = JsonConvert.SerializeObject(new JObject (
from card in CardListViewModel.CardList
select new JProperty(card.IndexName, card.CardImage.Src)));
答案 1 :(得分:0)
鉴于我无法修改POCO 并且您希望使用json.net,您可以为using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class CardListConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IEnumerable<Card>).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var list = existingValue as ICollection<Card> ?? new List<Card>();
var obj = JObject.Load(reader);
foreach (var property in obj.Properties())
{
list.Add(new Card { IndexName = property.Name, CardImage = new Image { Src = (string)property.Value } });
}
return list;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var collection = (IEnumerable<Card>)value;
writer.WriteStartObject();
foreach (var item in collection)
{
writer.WritePropertyName(item.IndexName);
writer.WriteValue(item.CardImage == null ? null : item.CardImage.Src);
}
writer.WriteEndObject();
}
}
类型的对象创建custom JsonConverter
作为如下:
var settings = new JsonSerializerSettings
{
Converters = { new CardListConverter() },
};
var json = JsonConvert.SerializeObject(CardListViewModel, Formatting.Indented, settings);
然后在序列化设置中使用它,如下所示:
CardListViewModel
您的{
"Id": "c2a7cc0f-0e6b-40a0-9020-aeba436265d4",
"CardList": {
"Visa": "Visa.png",
"MasterCard": "MasterCard.png"
}
}
将按如下方式序列化:
public void updateChild()
{
listaXBaldas.Clear();
listaYBaldas.Clear();
hueco1.updateChildAux();
hueco2.updateChildAux();
}
private void updateChildAux()
{
if (division == -1) return;
else
{
aux1 = balda.transform.position.y;
aux2 = balda.transform.position.x;
listaYBaldas.Add(aux1);
listaXBaldas.Add(aux2);
Debug.Log(listaXBaldas.Count);
hueco1.updateChildAux();
hueco2.updateChildAux();
}
}
示例fiddle。