I'm coding in C# for the .NET Framework 3.5.
I am trying to parse some Json to a JObject.
The Json is as follows:
{
"TBox": {
"Name": "SmallBox",
"Length": 1,
"Width": 1,
"Height": 2 },
"TBox": {
"Name": "MedBox",
"Length": 5,
"Width": 10,
"Height": 10 },
"TBox": {
"Name": "LargeBox",
"Length": 20,
"Width": 20,
"Height": 10 }
}
When I try to parse this Json to a JObject, the JObject only knows about LargeBox. The information for SmallBox and MedBox is lost. Obviously this is because it is interpreting "TBox" as a property, and that property is being overwritten.
I am receiving this Json from a service that's coded in Delphi. I'm trying to create a C# proxy for that service. On the Delphi-side of things, the "TBox" is understood as the type of the object being returned. The inner properties ("Name", "Length", "Width", "Height") are then understood as regular properties.
I can serialize and deserialize a custom 'TBox' object that has Name, Length, Width, and Height properties. That's fine.
What I want to do is step through all the TBox sections in such a way as to extract the following three Json strings.
First:
{
"Name": "SmallBox",
"Length": 1,
"Width": 1,
"Height": 2 }
Second:
{
"Name": "MedBox"
"Length": 5,
"Width": 10,
"Height": 10 }
Third:
{
"Name": "LargeBox"
"Length": 20,
"Width": 20,
"Height": 10 }
Once I have these strings, I can serialize and deserialize to my heart's content.
I'm finding Newtonsoft.Json to be very good. I really don't want to go messing about with other frameworks if I can avoid it.
Any help would be greatly appreciated.
I have very limited input as to changes that can be made to the server.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
JsonTextReader jsonReader = new JsonTextReader(reader);
jsonReader.Read();
while(jsonReader.Read())
{
if(jsonReader.TokenType == JsonToken.StartObject)
{
JObject tbox = JObject.Load(jsonReader);
}
}
However, note that the RFC says, "The names within an object SHOULD be unique" so if you can, recommend the format be changed.
EDIT: Here's an alternate design that doesn't have duplicate keys:
[
{
"TBox": {
"Width": 1,
"Length": 1,
"Name": "SmallBox",
"Height": 2
}
},
{
"TBox": {
"Width": 10,
"Length": 5,
"Name": "MedBox",
"Height": 10
}
},
{
"TBox": {
"Width": 20,
"Length": 20,
"Name": "LargeBox",
"Height": 10
}
}
]
If I'm not mistaken, the correct answer to this is that your input is not actually JSON. So no, getting a JSON parser to parse it probably isn't going to work.
Maybe you don't have any control over the source of the input, so I'd use a Regex or something to pre-filter the string. Turn it into something like:
{"TBoxes":
[
{
"Name": "SmallBox",
"Length": 1,
"Width": 1,
"Height": 2
},
{
"Name": "MedBox",
"Length": 5,
"Width": 10,
"Height": 10
},
{
"Name": "LargeBox",
"Length": 20,
"Width": 20,
"Height": 10
}
]
}
And treat it like the array that it is.
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