2017-04-26 14 views
0

重新排列您是如何使在c#C#JSON與同值

[ 
{"file": "fileName1", "key":0, title:"u1"}, 
{"file": "fileName1", "key":2, title:"u1"}, 
{"file": "fileName2", "key":5, title:"u1"}, 
{"file": "fileName2", "key":10, title:"u1"} 
] 

以下JSON到此。

{ 
"fileName1" : [{"key":0, title:"u1"},{"key":2, title:"u1"}], 
"fileName2" : [{"key":0, title:"u1"},{"key":2, title:"u1"}] 
} 

謝謝

+5

好了,後者看起來像它實際上是一個'詞典<字符串,列表>'。基本上我會反序列化爲一種類型,將其轉換爲另一種類型,然後將其序列化。你有沒有嘗試過嗎?如果是這樣,你卡在哪裏? –

回答

1

我已經做了.NET搗鼓你要求 https://dotnetfiddle.net/Wsnl9V

using System; 
using System.Collections.Generic; 
using System.Linq; 
using Newtonsoft.Json; 


public class Program 
{ 
    public static void Main() 
    { 
     string input = @"[ 
      {'file': 'fileName1', 'key':0, title:'u1'}, 
      {'file': 'fileName1', 'key':2, title:'u1'}, 
      {'file': 'fileName2', 'key':5, title:'u1'}, 
      {'file': 'fileName2', 'key':10, title:'u1'} 
     ]"; 

     var existingList = JsonConvert.DeserializeObject<List<CurrentType>>(input); 

     var dictionary = new Dictionary<string,List<RequiredTypeFile>>(); 


     var distinctFileNames = existingList.Select(x=> x.File).Distinct().ToList(); 

     distinctFileNames.ForEach(x=> 
            { 
             var fileValue = existingList.Where(m=>m.File==x) 
             .Select(m => new RequiredTypeFile 
               { 
                Key = m.Key, 
                Title = m.Title 
               }).ToList(); 
             dictionary.Add(x,fileValue); 
            }); 

     var reqdJson = JsonConvert.SerializeObject(dictionary); 


     Console.WriteLine(reqdJson); 
    } 
} 

public class CurrentType 
{ 
    public string File 
    { 
     get; 
     set; 
    } 

    public int Key 
    { 
     get; 
     set; 
    } 

    public string Title 
    { 
     get; 
     set; 
    } 
} 

public class RequiredTypeFile 
{ 
    public int Key 
    { 
     get; 
     set; 
    } 

    public string Title 
    { 
     get; 
     set; 
    } 

}