[英]convert json to another structure
我試圖通過具有不同類別和類型的列表來轉換結構,並將它們組合為diff結構(按類型名稱分組)。
我已經將整個結構放在jsfiddle中
該計划是要了解如何使用javascript或c#進行操作。
var fromJson = [
{
"type" : "Chicken",
"total" : 1,
"category" : "healthy"
},
{
"type" : "Pig",
"total" : 10,
"category" : "healthy"
},
{
"type" : "Pig",
"total" : 5,
"category" : "unhealthy"
},
{
"type" : "Cow",
"total" : 15,
"category" : "healthy"
}
];
至
var final_out = [
{
"type" : "chicken",
"healthy" : 1,
"unhealthy" : 0
},
{
"type" : "Pig",
"healthy" : 10,
"unhealthy" : 5
},
{
"type" : "Cow",
"healthy" : 15,
"unhealthy" : 0
}
]
嘗試:
public class RootObject
{
List<RootType> rootType;
}
public class RootType
{
public int healthy { get; set; }
public int unhealthy { get; set; }
}
要不就:
public class RootObject
{
public string type { get; set; }
public int healthy { get; set; }
public int unhealthy { get; set; }
}
因此,不要修改集合,而是嘗試刪除實際對象,然后使用更新的數據再次將其添加回去。 我為此使用Linq
。
以下是我匯總的一個小功能。
public string ReturnFinalOutput(string InputJson)
{
List<fromJson> input = JsonConvert.DeserializeObject<List<fromJson>>(InputJson);
List<final_out> output = new List<final_out>();
foreach (fromJson j in input)
{
final_out o = new final_out();
var finalout = output.FirstOrDefault<final_out>(a => a.type == j.type);
if (finalout == null)
{
o.type = j.type;
if (j.category == "healthy")
{
o.healthy = o.healthy + 1;
}
else if (j.category == "unhealthy")
{
o.unhealthy = o.unhealthy + 1;
}
output.Add(o);
}
else
{
output.Remove(finalout);
if (j.category == "healthy")
{
finalout.healthy = finalout.healthy + 1;
}
else if (j.category == "unhealthy")
{
finalout.unhealthy = finalout.unhealthy + 1;
}
output.Add(finalout);
}
}
return JsonConvert.SerializeObject(output);
}
下面是我的BaseClasses
public class fromJson
{
public string type { get; set; }
public int total { get; set; }
public string category { get; set; }
}
public class final_out
{
public string type { get; set; }
public int healthy { get; set; } = 0;
public int unhealthy { get; set; } = 0;
}
您可以將其稱為
string final_out = ReturnFinalOutput(fromJson); // fromJson is your InputJson.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.