2017-07-20 104 views
0

我正在尋找一種方法將動態JSON返回給用戶。 (就像在JavaScript中,你可以簡單地添加到JSON,無論你想要什麼)使用convertAll更改數據結構

我想改變一個數據結構爲我使用的另一個數據結構convertAll

請看看這裏:

public dynamic SomeActionMethod() 
{ 
    return Test_Get(). /* List<someClass> */ 
    ConvertAll(x => 
    { 
     if (someConditionToCheckAgainst) 
     { 
      return new 
      { 
       subValue1 = x 
      }; 
     } 
     else 
     { 
      return new 
      { 
       subValue2 = x      
      } 
     { 

    }; 
} 

我得到以下錯誤:

List.ConvertAll(Converter)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

在這裏做什麼?

+0

代碼不是像 – EpicKip

+0

你說得對,我會改變這種情況。 – user7425470

回答

0

這不是最靈活的方式來做到這一點(見JObject,Json.Net系列化指南),但是這能爲你的工作,例如:

public class Item 
{ 
    public int? month { get; set; } 
    public int? total { get; set; } 
} 

var intList = new List<int> { 4, 12 }; 
var resultList = intList.ConvertAll(r => 
{ 
    if (r == 4) 
    { 
     return new Item { month = r }; 
    } 
    else 
    { 
     return new Item { total = r }; 
    } 
}); 

var json = JsonConvert.Serialize(intList, Formatting.None, 
    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); 

注意monthtotal字段爲空。使用指定的設置進行序列化將不會包含空字段以生成json。

Json的將是這樣的:有問題[{ "month": 4 }, { "total": 12 }]

+0

我得到'類型'MyCustomClass'必須是非空值類型,以便將其用作通用類型或方法'Nullable '中的參數'T',並且此時結果總是具有'subValue1'和'subValue2',有一次它是null而不是null。 – user7425470

+0

@ user7425470請顯示您嘗試執行的代碼 – opewix