当我使用 JsonConvert.SerializeObject 时,如何只获取值?我不需要像id,name等那样的重复词......
示例: {id:189,姓名:'Paul',年龄:31,} x {[189,'Paul',31]}
谢谢!
我需要使用PageList类
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 :(得分: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)));
}
答案 1 :(得分: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
枚举并自己打印值。