Reputation: 75
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.
Upvotes: 4
Views: 4598
Reputation: 840
Parsing json with JObject.Parse is adding extra curly brackets to the json data. You can remove it by adding (string) conversion keyword.
Example
JObject jsonData= JObject.Parse(jsonString);
var specificData = (string)jsonData[myJsonName1][myJsonName2]
Converting string is the key part here. That solved my problem.
Upvotes: 0
Reputation: 11364
,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.
Upvotes: 2