【问题标题】:Converting Jackson JSON object references to JSON.Net object references将 Jackson JSON 对象引用转换为 JSON.Net 对象引用
【发布时间】:2016-10-31 00:42:28
【问题描述】:

我需要能够使用 C#/JSON.Net 客户端反序列化由 Jackson(Java/Spring 服务器)生成的 JSON 字符串,同时保持对象引用完整。 Jackson 将 "@id":1...n 用于循环引用,而引用由单个整数表示。 JSON.Net 使用“$id”和“$ref”。

有人知道如何将 JSON 字符串从 Jackson 转换为 JSON.Net 兼容版本吗?

【问题讨论】:

  • 感谢您的贡献。您是否愿意编辑您的帖子,以便将其表述为一个问题,然后将您的解决方案移动到该问题的答案帖子中?这种格式在本网站上效果更好,并允许其他人提供其他可能的解决方案。
  • @Brian....完成,我希望现在可以了;-)
  • 谢谢!我做了一些非常小的修改,但其他方面看起来不错。

标签: java c# json jackson json.net


【解决方案1】:

这是我的解决方案:

为 JSON.Net 使用这些设置:

JsonSerializerSettings settings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};

使用这个拦截器来转换引用:

public static class JSONInterceptor
{
    public static string sanitizeJSON(string originalJSONFromJava)
    {
        // Get ID right from Jackson to JSON.Net
        string pattern = Regex.Escape(@"""@id"":") + "(\\d+)";
        string replacement = @"""$id"":""$1""";
        Regex rgx = new Regex(pattern);
        string output = rgx.Replace(originalJSONFromJava, replacement);

        // Convert Jackson reference in array
        pattern = @",(\d+)";
        replacement = @",{""$ref"":""$1""}";
        rgx = new Regex(pattern);
        output = rgx.Replace(output, replacement);

        // Convert single Jackson reference to ref
        pattern = Regex.Escape(@"""\\w+"":") + "(\\d+)";
        replacement = @"""$ref"":""$1""";
        rgx = new Regex(pattern);
        output = rgx.Replace(output, replacement);

        return output;
    }
}

像这样调用拦截器并反序列化:

asset = JsonConvert.DeserializeObject<Asset>(JSONInterceptor.sanitizeJSON(response), settings);

资产类具有以下布局:

public class Asset {

    ....

     // Parent asset
     public Asset parent;
     // Asset agents
     public List<Agents> agent;

     ....
}

所以,Jackson 产生了类似的东西:

{"@id":1,......."parent":{"@id":15,.....},"agents":[{"@id":6, ......},12,{...}]...}

需要转换成类似(JSON.Net)的东西:

{"$id":"1",...,"$ref":"15",....,"agents":[{...,"$ref":"6",...]}

这就是上面代码的作用。

希望这对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2016-06-17
    • 2018-07-19
    相关资源
    最近更新 更多