C# Parsing Json File with no name

2019-05-29 01:16发布

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.

3条回答
Fickle 薄情
2楼-- · 2019-05-29 02:05

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.

查看更多
三岁会撩人
3楼-- · 2019-05-29 02:11

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",
    ...
查看更多
老娘就宠你
4楼-- · 2019-05-29 02:17

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

  json = Regex.Replace(json , "\"\":", "\"playerName\":", RegexOptions.IgnorePatternWhitespace);
查看更多
登录 后发表回答