繁体   English   中英

将json转换为另一种结构

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM