I have a XYZ.Json file with following content.
{
"ABC": "Account",
"CDE": "Balance",
"EFG": "Enquiry"
}
Using the following code I'm trying to read and return JObject from this Json, but extra curly braces is added at the beginning and end of the json structure.
JObject obj1 = JObject.Parse(System.IO.File.ReadAllText(@".\XYZ\install\XYZ.json));
obj1:
{{
"ABC": "Account",
"CDE": "Balance",
"EFG": "Enquiry"
}}
I have tried this option, converting Jobject.Tostring() but it didn't work.
Also tried this code, but still I see the same issue.
Dictionary<string, string> dict = new Dictionary<string, string>();
JObject obj = JObject.Parse(System.IO.File.ReadAllText(@".\XYZ\install\XYZ.json));
foreach (JProperty prop in obj.Properties())
{
dict.Add(prop.Name, obj.GetValue(prop.Name).ToObject<string>());
};
JObject obj3 = JObject.Parse(JsonConvert.SerializeObject(dict));
obj3:
{{
"ABC": "Account",
"CDE": "Balance",
"EFG": "Enquiry"
}}
Please suggest if there are any other solutions.
,You have to convert dictionary to json format first
JObject obj = JObject.Parse(File.ReadAllText(@"C:\temp\test.txt"));
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (JProperty prop in obj.Properties())
{
dict.Add(prop.Name, obj.GetValue(prop.Name).ToObject<string>());
};
var entries = dict.Select(d => string.Format($@"""{d.Key}"": ""{d.Value}"""));
string convertedString = "{" + string.Join(",", entries) + "}";
JObject obj3 = JObject.Parse(convertedString);
obj3 will give you same object as the obj.
Double Curly braces are internal represenation of a Json object. You cant remove the doubly braces as thats how json is represented in a JObject. Conversion from Json to Dictionary and then back to Json works correctly in the code above.
Both obj and obj3 variables look like following.

NOTE: Your example only works with string: string json .. if you have strin:object, this wont work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With