我需要能够使用 C#/JSON.Net 客户端反序列化由 Jackson(Java/Spring 服务器)生成的 JSON 字符串,同时保持对象引用不变。 Jackson 使用 "@id":1...n 进行循环引用,而引用由单个整数表示。 JSON.Net 使用“$id”和“$ref”。
有人知道如何将 JSON 字符串从 Jackson 转换为 JSON.Net 兼容版本吗?
最佳答案
这是我的解决方案:
对 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);
Assets 类有这样的布局:
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",...]}
这就是上面的代码所做的。
希望这对某人有帮助。
关于java - 将 Jackson JSON 对象引用转换为 JSON.Net 对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40335191/