c# – 从JSON字符串中获取动态键的值

我有这个json字符串,我想获得每条记录的第4行(iValue,sValue).

我的问题是每个记录的密钥都不同(基于值的数据类型).

有没有办法在C#上做到这一点?

这是一个例子:

{ "data": [
        {
          "pKey": "0",
          "Entity": "tableName",
          "Attribute": "CID",
          "iValue": "13"
        },
        {
          "pKey": "0",
          "Entity": "tableName",
          "Attribute": "username",
          "sValue": "test_user1"
        }] }

最佳答案 这是一个很大的实现,你必须为每个iValue,fValue等实现这个,但是,它加快了实现和使用.首先,这是用法:

string rawJson = "{\"data\":[{\"pKey\":\"0\",\"Entity\":\"tableName\",\"Attribute\":\"CID\",\"iValue\":\"13\"},{\"pKey\":\"0\",\"Entity\":\"tableName\",\"Attribute\":\"username\",\"sValue\":\"test_user1\"}]}";

var values = JsonConvert.DeserializeObject<TakeData>(rawJson).Data.Select(v => v.PureData);

现在值包含列表.以下是访问每个的用法:

foreach (var val in values)
{
    if (val is IntData i)
    {
        int myInt = i.iValue;
        // use the rest of the properties
    }
    else if (val is StrData s)
    {
        string myStr = s.sValue;
        // use the rest of the properties
    }
}

以下是实施:

class TakeData
{
    public List<TakeItAll> Data { get; set; }
}

class TakeItAll
{

    public int pKey { get; set; }
    public string Entity { get; set; }
    public string Attribute { get; set; }

    private int _iValue;
    public int iValue
    {
        get => _iValue;
        set
        {
            _iValue = value;
            PureData = new IntData { pKey = pKey, Entity = Entity, Attribute = Attribute, iValue = iValue };
        }
    }

    private string _sValue;
    public string sValue
    {
        get => _sValue;
        set
        {
            _sValue = value;
            PureData = new StrData { pKey = pKey, Entity = Entity, Attribute = Attribute, sValue = sValue };
        }
    }

    public IPureData PureData { get; private set; }

}

interface IPureData
{
    int pKey { get; set; }
    string Entity { get; set; }
    string Attribute { get; set; }
}

class IntData : IPureData
{
    public int pKey { get; set; }
    public string Entity { get; set; }
    public string Attribute { get; set; }
    public int iValue { get; set; }
}

class StrData : IPureData
{
    public int pKey { get; set; }
    public string Entity { get; set; }
    public string Attribute { get; set; }
    public string sValue { get; set; }
}

当然你也可以使用一些替代品.比如在TakeItAll中使用枚举来跟踪数据类型(或类型变量)而不是那么多类.这种方式然而,值对象的大小会更大.

class TakeItAll
{

    public int pKey { get; set; }
    public string Entity { get; set; }
    public string Attribute { get; set; }

    private int _iValue;
    public int iValue
    {
        get => _iValue;
        set
        {
            _iValue = value;
            ValType = typeof(string);
        }
    }

    private string _sValue;
    public string sValue
    {
        get => _sValue;
        set
        {
            _sValue = value;
            ValType = typeof(int);
        }
    }

    public Type ValType { get; private set; }

}
点赞