Newtonsoft Converter FromJson - 意想不到的令牌



我一直在尝试编写 JSON 反序列化器一段时间,但无法找到我的错误。为什么牛顿软件在反序列化后告诉我,Unexpected token when deserializing object: StartObject

type ThisFails =
  { a : string * string
    m : Map<string, string> }
type ThisWorks =
  { y : Map<string, string>
    z : string * string }
testCase "failing test - array before object" <| fun _ ->
  let res = deserialise<ThisFails> Serialisation.converters
                                   """{"a":["xyz","zyx"],"m":{}}"""
  Assert.Equal("should be eq to res", { a = "xyz", "zyx"; m = Map.empty }, res)
testCase "passing test - array after object" <| fun _ ->
  let res = deserialise<ThisWorks> Serialisation.converters
                                   """{"y":{},"z":["xyz","zyx"]}"""
  Assert.Equal("should be eq to res", { y = Map.empty; z = "xyz", "zyx" }, res)

主题是TupleArrayConverter。

该转换器的跟踪是:

reading json [Newtonsoft.Json.FSharp.TupleArrayConverter]
  type => System.Tuple`2[System.String,System.String]
value token, pre-deserialise [Newtonsoft.Json.FSharp.TupleArrayConverter]
  path => "a[0]"
  token_type => String
value token, post-deserialise [Newtonsoft.Json.FSharp.TupleArrayConverter]
  path => "a[1]"
  token_type => String
value token, pre-deserialise [Newtonsoft.Json.FSharp.TupleArrayConverter]
  path => "a[1]"
  token_type => String
value token, post-deserialise [Newtonsoft.Json.FSharp.TupleArrayConverter]
  path => "a"
  token_type => EndArray
after EndArray token, returning [Newtonsoft.Json.FSharp.TupleArrayConverter]
  path => "m"
  token_type => PropertyName

在转换器中,我正在使用最后一个令牌,即结束数组,如您在终止案例中看到的那样:

match reader.TokenType with
| JsonToken.EndArray ->
  read JsonToken.EndArray |> req |> ignore
  acc

而且我在一开始就使用了 StartArray 令牌...

那么:为什么这段代码不起作用?(Newtonsoft.json 6.0.8)

这是错误:

map tests/failing test - array before object: Exception: Newtonsoft.Json.JsonSerializationException: Unexpected token when deserializing object: StartObject. Path 'm', line 1, position 24.
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ResolvePropertyAndCreatorValues (Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty containerProperty, Newtonsoft.Json.JsonReader reader, System.Type objectType, IDictionary`2& extensionData) [0x00000] in <filename unknown>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectUsingCreatorWithParameters (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty containerProperty, Newtonsoft.Json.Serialization.ObjectConstructor`1 creator, System.String id) [0x00000] in <filename unknown>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract objectContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, Newtonsoft.Json.Serialization.JsonProperty containerProperty, System.String id, System.Boolean& createdFromNonDefaultCreator) [0x00000] in <filename unknown>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00000] in <filename unknown>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00000] in <filename unknown>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent) [0x00000] in <filename unknown>:0  (00:00:00.1500996)
1 tests run: 0 passed, 0 ignored, 0 failed, 1 errored (00:00:00.2482623)

一直在调试代码和 JSON.Net。

事实证明,在失败的情况下使用EndArray令牌后,读取器指向一个PropertyName令牌,这很好。

然后在转换器完成执行后 JSON.Net 执行此操作。

} while (!exit && reader.Read());

然后,Read()将读取器移动到下一个令牌,在失败的情况下,该令牌StartObject导致反序列化程序失败。

因此,我不是 JSON.Net 的专家,但考虑为字符串值提供提供程序 JSON.Net 我可能不会在转换后推进读者,这意味着读者仍然指向字符串值。按照同样的思路,在使用数组时,将读取器留在数组值的最后一个令牌(即EndArray令牌)是有意义的。

所以我的建议只是这样:

match reader.TokenType with
| JsonToken.EndArray ->
//    read JsonToken.EndArray |> req |> ignore
  Logger.debug logger <| fun _ ->
    LogLine.sprintf
      [ "path", reader.Path |> box
        "token_type", reader.TokenType |> box ]
      "after EndArray token, returning"
  acc

这使我的测试程序:

[<EntryPoint>]
let main argv = 
    let works = deserialize<ThisWorks> """{"y":{},"z":["xyz","zyx"]}"""
    printfn "%A" works
    let fails = deserialize<ThisFails> """{"a":["xyz","zyx"],"m":{}}"""
    printfn "%A" fails
    0

打印

{y = map [];
 z = ("xyz", "zyx");}
{a = ("xyz", "zyx");
 m = map [];}

希望这可以帮助您解决此错误(您可能已经这样做了)

相关内容

  • 没有找到相关文章

最新更新