2

So, part of the Json file is like this:

{
"number":"23",
"name":{
    "":"LJames"   <----------- look at this line
},
"Gender":"Male",
...

I am trying to parse this, and as long as the name field is there (without a name match with the value), the DataContractJsonSerializer will fail to read it.

Anyone has experience with this kind of Json file please share some idea, thank you.

Allan Jiang
  • 11,063
  • 27
  • 104
  • 165

3 Answers3

2

You could try using Json.NET to parse it. It generally works a lot better than DataContractJsonSerializer and has better performance. I'm not sure if that would solve your problem though.

If you think about it, what would the resulting object look like in C#? From a JSON string like this...

{
     "name" : { "first" : "James" }
}

...I would expect to map to a C# object with a "name" property, and that "name" property would reference an object with a "first" property (which would be a string, with a value of "James").

So if you remove the key value "first", how will the parser know how to map (or how to name) the property? There's no such thing as a nameless property in C#.

I would suggest reformatting your Json file (if possible) to look like so:

{
    "number":"23",
    "name": "LJames",
    "Gender":"Male",
    ...
Spectre87
  • 2,374
  • 1
  • 24
  • 37
  • +1. Writing a band-aid to fix source data always leads to more band-aids. – Daniel Szabo Jul 06 '12 at 00:39
  • +1 and best answer. I solved this by simply replacing all `""` in the Json file by something like `"undefinedField"` and parse it. – Allan Jiang Jul 06 '12 at 01:13
  • 1
    @AllanJiang, just to warn you that you should not replacing all `""`. If you do so you may replace a property value(not name) with that "undefinedField". I guess you should try to replace `""(any number of spaces):` with `"undefinedField" :`. – 000 Jul 06 '12 at 01:37
2

Use Regular Expressions to replace this empty quote with a variable name of your choice, for example:

  json = Regex.Replace(json , "\"\":", "\"playerName\":", RegexOptions.IgnorePatternWhitespace);
Misha
  • 571
  • 5
  • 17
0

There is a library called jansson for C and C++. I'm not familiar with C# but there is no reason for it not work there either. However, if you want to create a parser yourself, I would tell you, write a regex as your delim: For example String delim = "{} :\n\t"; Your parser is basically: If : on the line, then retrieve value as a key : value pair, if { keep parsing until } is found. I doubt you would have any trouble writing such parser.

cybertextron
  • 10,547
  • 28
  • 104
  • 208