2012-05-10 19 views
1

當我使用JsonConvert.SerializeObject時,我怎樣才能得到值?我不需要像ID,名稱等重複字詞...Json.NET僅輸出C#中的值

例如:{id:189,name:'Paul',age:31,} x {[189,'Paul',31] }

謝謝!

我需要分頁類

public class PageList { 
    IEnumerable _rows; 
    int _total; 
    int _page; 
    int _records; 
    object _userData; 

    public PageList(IEnumerable rows, int page, int total, int records, object userData) { 
     _rows = rows; 
     _page = page; 
     _total = total; 
     _records = records; 
     _userData = userData; 
    } 

    public PageList(IEnumerable rows, int page, int total, int records) 
     : this(rows, page, total, records, null) { 

    } 

    public int total { get { return _total; } } 

    public int page { get { return _page; } } 

    public int records { get { return _records; } } 

    public IEnumerable rows { get { return _rows; } } 

    [JsonIgnore] 
    public object userData { get { return _userData; } } 

    public override string ToString() { 
     return Newtonsoft.Json.JsonConvert.SerializeObject(this, new IsoDateTimeConverter() { DateTimeFormat = "dd-MM-yyyy hh:mm:ss" }); 
    } 
} 
+0

您將如何參考屬性,當您發送對第二件事情?然後你可以堅持陣列。 – leppie

回答

2

我能想到的最接近的是

var yourObjectList = List<YourObject>(){.....} 

string s = JsonConvert.SerializeObject(GetObjectArray(yourObjectList)); 

public static IEnumerable<object> GetObjectArray<T>(IEnumerable<T> obj) 
{ 
    return obj.Select(o => o.GetType().GetProperties().Select(p => p.GetValue(o, null))); 
} 
+0

謝謝,我嘗試使用Pagelist類,但在嘗試在GetObjectArray(yourObjectList)中使用IEnumerable時出錯,您有任何建議嗎? –

1

第二個是不是有效的JSON({ 189, 'Paul', 31 })使用。也許你需要一個數組([ 189, 'Paul', 31 ]),在這種情況下,你可以不直接使用串行器,首先將對象加載到JObject,然後只取其值。

public class Foo 
{ 
    public int id; 
    public string name; 
    public int age; 
} 

public class Test 
{ 
    public static void Main() 
    { 
     Foo foo = new Foo { id = 189, name = "Paul", age = 31 }; 
     JObject jo = JObject.FromObject(foo); 
     JArray ja = new JArray(); 
     foreach (var value in jo.Values()) 
     { 
      ja.Add(value); 
     } 

     Console.WriteLine(ja); 
    } 
} 

或者,如果你真的想非JSON格式,還可以使用JObject枚舉和自己打印值。

+0

謝謝,你能幫我使用PageLList類嗎? –