【问题标题】:JSON Serializer is giving an issue, when the Json string contains string and array of strings当 Json 字符串包含字符串和字符串数组时,JSON 序列化程序会出现问题
【发布时间】:2012-05-16 14:03:55
【问题描述】:

当 Json 字符串包含 'key1:value1' 时,可以将其转换为 Dictionary 类型。

但在我的例子中,它还包含一个字符串数组以及上面的键:值,即:

{k1:v1; "key2\":[{\"Key11\":{\"key21\":\"Val21\",\"key22\":\"val22\"}]

(Json 数据包含一些字符串和一些数组。)

当我使用 Dictionary 或 Dictionary 时 - 它在值作为字符串时失败 - 无法将字符串转换为字符串 [] 等。

仍然可以使用 Dictionary,但是有没有更好的方法来处理呢?

谢谢 帕尼

【问题讨论】:

  • 是你写的那样的固定结构,还是你在寻找一个通用的解决方案?
  • 通用解决方案,假设我们不知道结构...

标签: json string serialization arraylist


【解决方案1】:

如果您在编译时不知道结构,那么就没有其他方法可以序列化 JSON 字符串——它必须是 Dictionary。但是,如果您使用的是 C# 4.0,则可以使用 DynamicObject。由于动态类型将类型解析推迟到运行时,如果您使用这种方法进行序列化,您可以将您的序列化对象视为强类型(尽管没有编译时支持)。这意味着您可以使用 JSON 样式的点表示法来访问属性:

MyDynamicJsonObject.key2

为此,您可以从 DynamicObject 继承,并实现 TryGetMember 方法(quoted from this link, which has a full implementation):

public class DynamicJsonObject : DynamicObject
{
    private IDictionary<string, object> Dictionary { get; set; }

    public DynamicJsonObject(IDictionary<string, object> dictionary)
    {
        this.Dictionary = dictionary;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = this.Dictionary[binder.Name];

        if (result is IDictionary<string, object>)
        {
            result = new DynamicJsonObject(result as IDictionary<string, object>);
        }
        else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
        {
            result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
        }
        else if (result is ArrayList)
        {
            result = new List<object>((result as ArrayList).ToArray());
        }

        return this.Dictionary.ContainsKey(binder.Name);
    }
}

请注意,动态类型目前不支持索引器表示法,因此对于数组,您需要implement a workaround using notation like this

MyDynamicJsonObject.key2.Item(0)

【讨论】:

    【解决方案2】:

    您的示例不是有效的 JSON,例如每个键和值都应该用" 包围,例如{"k1":"v1"},左大括号和右大括号的数量必须匹配,如果你使用\"转义"字符,你必须添加另一个"字符,例如"key2\""

    使用JSONLint 等工具来验证您的 JSON 是否正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 2023-03-04
      • 2019-04-03
      • 1970-01-01
      • 2020-11-23
      相关资源
      最近更新 更多