首页 > 解决方案 > 没有 id 的 Json Net $ref

问题描述

我想使用 $ref 指向属性而不是对象中的 id。

具体来说,在下面的示例中,我希望AlternateAdress指向Address1中的城市属性

 String str3 = "{
   'Name': 'Jon Smith',
   'Address1': { '$id': '1', 'City': 'New York', 'State': 'NY'},
   'AlternateAddress':{'$ref':'#/Address1/City'}}"; 

Person  stuff = JsonConvert.DeserializeObject<Person>(str3, settings);

Console.WriteLine(stuff.AlternateAddress);

上面的代码返回错误

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'AlternateAddress', line 1, position 105.
   at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
   at Newtonsoft.Json.JsonTextReader.ReadAsString()
   at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Rextester.Program.Main(String[] args)

标签: c#jsonjson.net

解决方案


推荐阅读