Reputation: 51
I need to be able to deserialize a JSON string produced by Jackson (Java/Spring server) with a C#/JSON.Net client while keeping the object references intact. Jackson uses "@id":1...n for cyclic references, while the reference is denoted by a single integer. JSON.Net uses "$id" and "$ref".
Does anybody know how to convert a JSON string from Jackson to a JSON.Net compatible version?
Upvotes: 2
Views: 1423
Reputation: 51
Here is my solution:
Use these settings for JSON.Net:
JsonSerializerSettings settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
Use this interceptor to convert the references:
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;
}
}
Call the interceptor and deserialize like this:
asset = JsonConvert.DeserializeObject<Asset>(JSONInterceptor.sanitizeJSON(response), settings);
The asset class has this layout:
public class Asset {
....
// Parent asset
public Asset parent;
// Asset agents
public List<Agents> agent;
....
}
So, Jackson produces something like:
{"@id":1,......."parent":{"@id":15,.....},"agents":[{"@id":6, ......},12,{...}]...}
which needs to be converted into something like (JSON.Net):
{"$id":"1",...,"$ref":"15",....,"agents":[{...,"$ref":"6",...]}
This is what the code above does.
Hope this helps somebody.
Upvotes: 1