微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有这个json字符串,我想获得每条记录的第4行(iValue,sValue).
我的问题是每个记录的密钥都不同(基于值的数据类型).

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

这是一个例子:

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

解决方法

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

string rawJson = "{\"data\":[{\"pKey\":\"0\",\"Entity\":\"tableName\",\"Attribute\":\"CID\",\"iValue\":\"13\"},{\"pKey\":\"0\",\"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,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; }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐