创建指定格式Json的正确方法

时间:2018-04-01 22:05:32

标签: c# json serialization format

我尝试序列化对象列表以获取下面的json结果:

 [
  {
        "nolan_dorris": [{
            "created_at": "Mon Sep 24 03:35:21 +0000 2012",
            "profile_link": "https://twitter.com/nolan_dorris",
            "favorite_count": 274,
            "screen_name": "nolan_dorris",
            "followers_count": 951,
            "link": "https://twitter.com/nolan_dorris/status/574184",
            "text": "Use the multi-byte AGP system, then you can calculate t @locaweb ",
            "retweet_count": 0
        }]
    },
    {
        "imogene_kovacek": [{
            "screen_name": "imogene_kovacek",
            "profile_link": "https://twitter.com/imogene_kovacek",
            "created_at": "Mon Sep 24 03:35:21 +0000 2012",
            "favorite_count": 140,
            "followers_count": 735,
            "text": "You can't hack the hard drive without backing up the optical @locaweb ",
            "link": "https://twitter.com/imogene_kovacek/status/823386",
            "retweet_count": 0
        }]
    }
]

我的班级

public class TweetDto
{
    public string created_at { get; set; }
    public string profile_link { get; set; }
    public int favorite_count { get; set; }
    public string screen_name { get; set; }
    public int followers_count { get; set; }
    public string link { get; set; }
    public string text { get; set; }
    public int retweet_count { get; set; }
}

序列化TweetDto列表的方法

 public static string SerializeTweets<T>(T list)
    {
        string json = string.Empty;
        try
        {
            json = JsonConvert.SerializeObject(list, Formatting.Indented);
        }
        catch (Exception) { }
        return json;
    }

使用NewtonSoft.Json库我尝试执行序列化,但是我无法达到所需的格式,指示对象的键是twitter中配置文件的名称。如何以这种格式生成json文件?

2 个答案:

答案 0 :(得分:2)

简答

如果您以List<TweetDto>开头,则以下操作会生成您在问题中要求的结构。

var mapped = list
    .GroupBy(dto => dto.screen_name)
    .Select(group => new Dictionary<string, List<TweetDto>> 
    {
        { group.Key, group.ToList() }
    });

var json = JsonConvert.SerializeObject(mapped, Formatting.Indented);

实施例

为了节省空间,该示例使用您定义的原始TweetDto类的子集。这说它也适用于原来的TweetDto类。

var list = new List<TweetDto> 
{
    new TweetDto
    {
        screen_name = "nolan_dorris",
        text = "Some text"
    },
    new TweetDto
    {
        screen_name = "nolan_dorris",
        text = "Some other text"
    },
    new TweetDto
    {
        screen_name = "imogene_kovacek",
        text = "Some text"
    }
};

var mapped = list
    .GroupBy(dto => dto.screen_name)
    .Select(group => new Dictionary<string, List<TweetDto>> 
    {
        { group.Key, group.ToList() }
    });

var json = JsonConvert.SerializeObject(mapped, Formatting.Indented);

Console.WriteLine(json);

这是输出,与您在问题中要求的结构相同。

[
  {
    "nolan_dorris": [
      {
        "screen_name": "nolan_dorris",
        "text": "Some text"
      },
      {
        "screen_name": "nolan_dorris",
        "text": "Some other text"
      }
    ]
  },
  {
    "imogene_kovacek": [
      {
        "screen_name": "imogene_kovacek",
        "text": "Some text"
      }
    ]
  }
]

答案 1 :(得分:0)

关注Json.NET Documentation的文档。我根据我的要求手动设置了json

 var groupedList = users.GroupBy(sn => sn.screen_name).ToList();

        JArray root = new JArray();
        JObject profileGroup = new JObject();

        for (int i = 0; i < groupedList.Count; i++)
        {
            JArray tweets = new JArray();
            JObject tweet;
            foreach (var item in groupedList[i].ToList())
            {
                tweet = new JObject();
                tweet["created_at"] = item.created_at;
                tweet["profile_link"] = item.profile_link;
                tweet["favorite_count"] = item.favorite_count;
                tweet["screen_name"] = item.screen_name;
                tweet["followers_count"] = item.followers_count;
                tweet["link"] = item.link;
                tweet["text"] = item.text;
                tweet["retweet_count"] = item.retweet_count;

                tweets.Add(tweet);
            }
            profileGroup[groupedList[i].Key] = tweets;
        }

以下是我的测试结果,其中推文按screen_nam分组,在此测试中,screen_name aaaa 在json中有3条推文,其他只有1条。

[
  {
"aaaaa": [
  {
    "created_at": "Mon Sep 24 03:35:21 +0000 2012",
    "profile_link": "",
    "favorite_count": 10,
    "screen_name": "aaaaa",
    "followers_count": 10,
    "link": "",
    "text": "@locaweb 11",
    "retweet_count": 10
  },
  {
    "created_at": "Mon Sep 24 03:35:21 +0000 2012",
    "profile_link": "",
    "favorite_count": 10,
    "screen_name": "aaaaa",
    "followers_count": 10,
    "link": "",
    "text": "@locaweb 22",
    "retweet_count": 10
  },
  {
    "created_at": "Mon Sep 24 03:35:21 +0000 2012",
    "profile_link": "",
    "favorite_count": 10,
    "screen_name": "aaaaa",
    "followers_count": 10,
    "link": "",
    "text": "@locaweb 23",
    "retweet_count": 10
  }
],
"bbbbb": [
  {
    "created_at": "Mon Sep 24 03:35:21 +0000 2012",
    "profile_link": "",
    "favorite_count": 20,
    "screen_name": "bbbbb",
    "followers_count": 20,
    "link": "",
    "text": "@locaweb 22",
    "retweet_count": 20
  }
],
"cccc": [
  {
    "created_at": "Mon Sep 24 03:35:21 +0000 2012",
    "profile_link": "",
    "favorite_count": 30,
    "screen_name": "cccc",
    "followers_count": 30,
    "link": "",
    "text": "@locaweb 33",
    "retweet_count": 30
  }
]
}
]