Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

c# - Deserializing nested JSON structure to a flattened class with Json.NET using annotations

Is it possible to use JsonProperty annotation to map a nested Json property to a non-nested .NET member? Say you've got some Json like this:

{
     "id":9999,
     "created_date":"Thu, 23 Jun 2011 12:56:24 +0000",
     "pos":{
        "type":"someType",
        "coordinates":[
           59.323,
           18.0654
        ]
     }
}

and want to deserialize it into a flattened class MyClass using

JsonConvert.DeserializeObject<MyClass>(jsonstr);

Can annotations be used to map the Json coordinates list to Lat and Lng in the class below:

public class MyClass {
   [JsonProperty("id")]
   public int Id { get; set; }
   [JsonProperty("created_date")]
   public DateTime Created { get; set; }
   [JsonProperty("????")]
   public float Lat { get; set; }
   [JsonProperty("?????")]
   public float Lng { get; set; }
}

Just curious. I can always define the class like this and it seems to work fine:

public class MyClass {
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("date_created")]
    public DateTime Created { get; set; }
    [JsonProperty("pos")]
    public PosClass Pos { get; set; }
}

public class PosClass
{
    public List<float> coordinates { get; set; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From personal experience, I struggled before trying to re-use my entities for communication (JSON, XML ... etc.) but after paying closer attention to existing patterns, I found out that having "data transfer objects" in addition to internal / storage entities that you already have will liberate my communication models and the only cost I paid was to accept doing manual, yet straight-forward, effort of manually-coded conversion between the two.

If you'd rather stick to what you have and performance is no big deal, then .NET reflection is your friend.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...