将json转换为另一个结构

时间:2017-02-02 17:41:30

标签: c# arrays json

我试图通过使用具有不同类别和类型的列表来转换结构,并将它们组合到diff结构(按类型名称分组)。

我已将完整结构放在jsfiddle here

计划是了解如何使用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
  }
]

2 个答案:

答案 0 :(得分: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; }
}

答案 1 :(得分:0)

因此,不要修改集合,尝试删除实际对象并使用更新的数据再次添加它。我为此使用了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.