zoukankan      html  css  js  c++  java
  • toJSON

    View Code
    public static string ToJSON(IEnumerable array, params string[] propertyNames)
    {
    Guard
    <ArgumentNullException>(array == null || propertyNames == null);
    if (propertyNames.Length > 0)
    {
    IEnumerator tor
    = array.GetEnumerator();
    if (tor.MoveNext())
    {
    StringBuilder json
    = new StringBuilder("[{");
    object entity = tor.Current;
    Type type
    = entity.GetType();
    PropertyInfo property;
    foreach (string name in propertyNames)
    {
    property
    = type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
    if (property != null)
    {
    json.Append(property.Name).Append(
    ':');
    AppendJSONValue(json, property, GetPropertyAccess(property).GetValue(entity));
    json.Append(
    ',');
    }
    }
    json.Length
    --;
    json.Append(
    '}');
    while (tor.MoveNext())
    {
    entity
    = tor.Current;
    type
    = entity.GetType();
    json.Append(
    ",{");
    foreach (string name in propertyNames)
    {
    property
    = type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
    if (property != null)
    {
    json.Append(property.Name).Append(
    ':');
    AppendJSONValue(json, property, GetPropertyAccess(property).GetValue(entity));
    json.Append(
    ',');
    }
    }
    json.Length
    --;
    json.Append(
    '}');
    }
    return json.Append("]").ToString();
    }
    }
    return "[]";
    }

    private static void AppendJSONValue(StringBuilder buffer, PropertyInfo property, object value)
    {
    switch (Type.GetTypeCode(property.PropertyType))
    {
    case TypeCode.Boolean:
    buffer.Append(value.ToString().ToLower());
    break;
    case TypeCode.DateTime:
    DateTime time
    = Convert.ToDateTime(value);
    buffer.Append(
    "new Date(")
    .Append(time.Year).Append(
    ',')
    .Append(time.Month
    - 1).Append(',')
    .Append(time.Day).Append(
    ',')
    .Append(time.Hour).Append(
    ',')
    .Append(time.Minute).Append(
    ',')
    .Append(time.Second).Append(
    ')');
    break;
    case TypeCode.String:
    buffer.Append(
    '"').Append(value).Append('"');
    break;
    default:
    buffer.Append(value);
    break;
    }
    }
  • 相关阅读:
    代码中引用res里的颜色、图片
    time.setToNow() 取当前时间,月份有误
    adb报错:The connection to adb is down, and a severe&nbs
    安卓下拉刷新、上拉加载数据显示
    4、安卓数据存储——sqlite
    3、安卓数据存储——缓存、内存管理
    2、安卓数据存储——本地文件
    1、安卓数据存储机制——sharedPreference
    一个异步任务接收两个url下载两个图片
    adb报错:The connection to adb is down, and a severe&nbs
  • 原文地址:https://www.cnblogs.com/Googler/p/1955439.html
Copyright © 2011-2022 走看看