如何在没有属性名称的情况下将对象输出为json?

时间:2017-05-09 13:32:45

标签: c# json asp.net-web-api2

我有一个WebAPI 2项目,其中包含几个以Json格式返回数据的API。然后将这些Json文件加载到单独的前端开发机构创建的图形中。这些图形接受以下格式的Json文件:

"colors": {
    "Europe": "red",
    "North-America": "blue",
    "South-America": "green",
    "Asia": "purple",
    "Other": "grey"
}

我的WebAPI项目将数据输出为Json,但它包含如下属性名称:

"colors": [
{
  "Title": "Europe",
  "ColorName": "red"
},
{
  "Title": "North-America",
  "ColorName": "blue"
},
{
  "Title": "South-America",
  "ColorName": "green"
},
{
  "Title": "Asia",
  "ColorName": "purple"
},
{
  "Title": "Other",
  "ColorName": "grey"
}

是否有标准的方法来输出没有属性名称的数据?

我正在使用WebAPI 2的标准安装及其所有默认值,其中包括对Newtonsoft.Json的引用。

3 个答案:

答案 0 :(得分:2)

如果您使用的是json.net,一种方法是定义自定义JsonConverter

public class Color
{
    public string Title { get; set; }
    public string ColorName { get; set; }
}

public class ColorsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Color[]);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var colors = (Color[]) value;

        var temp = colors.ToDictionary(x => x.Title, x => x.ColorName);

        serializer.Serialize(writer, temp);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

然后使用它:

var colors = new[]
{
    new Color {Title = "Europe", ColorName = "red"},
    new Color {Title = "North-America", ColorName = "blue"},
    new Color {Title = "South-America", ColorName = "green"},
    new Color {Title = "Asia", ColorName = "purple"},
    new Color {Title = "Other", ColorName = "grey"}
};

var json = JsonConvert.SerializeObject(new {colors}, new ColorsConverter());

这将产生这样的json:

{
  "colors": {
    "Europe": "red",
    "North-America": "blue",
    "South-America": "green",
    "Asia": "purple",
    "Other": "grey"
  }
}

答案 1 :(得分:0)

如果你解码它 它将是相同的 它们都可以解码为json对象 它是一个有意义的和有希望的帮助

答案 2 :(得分:0)

当你得到api数据时,改变这样......

 $(document).ready(function () {

    //your api json data
    var rootObject = {
        "colors": [
{
"Title": "Europe",
"ColorName": "red"
},
{
"Title": "North-America",
"ColorName": "blue"
},
{
"Title": "South-America",
"ColorName": "green"
},
{
"Title": "Asia",
"ColorName": "purple"
},
{
"Title": "Other",
"ColorName": "grey"
}]
    }
    var jsonArr = [];
    for (var i = 0; i < rootObject.colors.length; i++) {
        var temp={};
        temp[rootObject.colors[i].Title] = rootObject.colors[i].ColorName;

        jsonArr.push(temp);
    }

    var stringJson = JSON.stringify(jsonArr);

    alert(stringJson );
    });