zoukankan      html  css  js  c++  java
  • c# json转换成dynamic对象,然后在dynamic对象中动态获取指定字符串列表中的值

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ConsoleApp1
    {
    class Program
    {
    static void Main(string[] args)
    {

    string ss = TestAA();
    Console.WriteLine(ss);
    Console.ReadKey();
    }

    private static string TestAA()
    {
    string allowAttr = string.Empty;
    string json = "{"UserName":"Jack","LoS":"Beijing","Group":"34"}";
    //此处模拟在不建实体类的情况下,反转将json返回成dynamic对象
    var DynamicObject = JsonConvert.DeserializeObject<dynamic>(json);
    //var _value = DynamicObject["LoS"];
    List<string> ssList = new List<string>();
    ssList.Add("LoS");
    ssList.Add("Test2");
    foreach(string item in ssList)
    {
    var value2 = DynamicObject[item];//动态获取字符串列表中的字段去dynamic对象中找对应字段的值
    if(value2!=null)
    {
    allowAttr = string.Format("{0}{1}", value2, "_Attribute");
    //string allowAttr2 = string.Format("{0}{1}", value2.Value, "_Attribute");
    }
    }

    return allowAttr;
    //Console.WriteLine(DynamicObject.LoS);
    //Type Ts = DynamicObject.GetType();
    //object o = Ts.GetProperty("Name").GetValue(DynamicObject, null);
    //string Value = Convert.ToString(o);
    //if (string.IsNullOrEmpty(Value))
    //{
    // return null;
    //}
    //else
    //{
    // return Value;
    //}
    }
    }
    }

  • 相关阅读:
    [NOIP2011] 玛雅游戏
    [bzoj4025] 二分图
    [10.2模拟] tree
    [10.3模拟] color
    [10.2模拟] teach
    [10.2模拟] plan
    [10.2模拟] book
    [bzoj4999] This Problem Is Too Simple!
    [9.28模拟] good
    [bzoj3884] 上帝与集合的正确用法
  • 原文地址:https://www.cnblogs.com/klsw/p/8641954.html
Copyright © 2011-2022 走看看