I'm trying to translate the content of a JSON document. This means that I have to translate the values of some properties, not all.
Isolating the problem, I'm trying to get all the properties with a specific name ( e.g title ), that can be at different json levels, then get the values of those properties, translate the value using a translation service, and replace back the value of each one with the translated value.
How can I achieve this using C#?. I'm trying to use Newtonsoft.Json library, and it's a bit confusing for me the usage of JToken, JProperty..
This is the example of the json file:
[
{
"_id": "a-10",
"_parentId": "co-10",
"_type": "article",
"_classes": "",
"title": "THINK INTEGRITY AT X",
"displayTitle": "SECTION 01: <em>THINK INTEGRITY AT X </em>",
"body": "<p>ASKING THE RIGHT QUESTIONS.</p>"
},
{
"_id": "a-20",
"_parentId": "co-20",
"_type": "article",
"_classes": "",
"title": "INTEGRITY OF SERVICES",
"displayTitle": "SECTION 02: <em>INTEGRITY OF SERVICES</em>",
"body": "<p>STAYING INDEPENDENT IN ALL CIRCUMSTANCES.</p>"
},
{
"_id": "a-30",
"_parentId": "co-30",
"_type": "article",
"_classes": "",
"title": "BRIBERY AND CORRUPTION",
"displayTitle": "SECTION 03: <em>BRIBERY AND CORRUPTION</em>",
"body": "<p>KNOWING WHAT YOU SHOULD AND SHOULDN'T ACCEPT.</p>"
},
{
"_id": "a-40",
"_parentId": "co-40",
"_type": "article",
"_classes": "",
"title": "CONFLICTS OF INTEREST",
"displayTitle": "SECTION 04: <em>CONFLICTS OF INTEREST</em>",
"body": "<p>RECOGNISING CONFLICTS AND KNOWING WHAT TO DO.</p>"
},
{
"_id": "a-50",
"_parentId": "co-50",
"_type": "article",
"_classes": "",
"title": "OPERATIONAL INTEGRITY",
"displayTitle": "SECTION 05: <em>OPERATIONAL INTEGRITY</em>",
"body": "<p>LEARN IT. OWN IT. BE IT.</p>"
},
{
"_id": "a-60",
"_parentId": "co-60",
"_type": "article",
"_classes": "",
"title": "TEST YOURSELF",
"displayTitle": "SECTION 06: <em>TEST YOURSELF</em>",
"body": "<p>PUTTING YOUR INTEGRITY TO THE TEST.</p>"
}
]
So to translate the content of the "title" property in all the json, can be like this:
string jsonText = File.ReadAllText(jsonfilename);
JArray jsonDocument = JArray.Parse(jsonText);
IEnumerable<JToken> titles = jsonDocument.SelectTokens("..title");
foreach (var title in titles)
{
string translatedText = TranslationService.TranslateString(title.ToString(), fromlanguage, tolanguage, "text/plain");
title.Replace(JToken.FromObject(new { title = translatedText }));
}
but this is not working, I think I'm close to it but I can't see the way to replace the property value with the translated one.
Remember that the title can be at any level in the JSON file, so to access using the jsonDocument["title"] way is not feasible, and I want to replace the existing value with the translated.
I'll appreciate any clue Thanks