简体   繁体   English

用JSON.net压缩成一个对象

[英]Condense into an object with JSON.net

I'm working with an API with an example output of the following 我正在使用以下示例输出的API

{
        "id": 12345678

        "photo-url-1280": "http://68.media.tumblr.com/5076e813bdc463409f59172b2c152487/tumblr_ocy8peMYvo1uur5s9o1_1280.png",
        "photo-url-500": "http://67.media.tumblr.com/5076e813bdc463409f59172b2c152487/tumblr_ocy8peMYvo1uur5s9o1_500.png",
        "photo-url-400": "http://68.media.tumblr.com/5076e813bdc463409f59172b2c152487/tumblr_ocy8peMYvo1uur5s9o1_400.png",
        "photo-url-250": "http://67.media.tumblr.com/5076e813bdc463409f59172b2c152487/tumblr_ocy8peMYvo1uur5s9o1_250.png",
        "photo-url-100": "http://67.media.tumblr.com/5076e813bdc463409f59172b2c152487/tumblr_ocy8peMYvo1uur5s9o1_100.png",
        "photo-url-75": "http://67.media.tumblr.com/5076e813bdc463409f59172b2c152487/tumblr_ocy8peMYvo1uur5s9o1_75sq.png",
}

Those last items are very related, so I'd like to move them into their own object. 这些最后一项非常相关,因此我想将它们移到自己的对象中。

As of now, getting a specified image would be super messy. 到目前为止,获取指定的图像将非常混乱。 Getting the 400px version might look like this - 获取400px版本可能看起来像这样-

myPhotoObject.Photo400

However, if I was able to move these URLs into an object of their own, I could more cleanly call it like the following: 但是,如果能够将这些URL移到它们自己的对象中,则可以更清晰地调用它,如下所示:

myPhotoObject.Photo.400

or even introduce more friendly methods 甚至介绍更友好的方法

myPhoto.Photo.GetClosestTo(451);

There is a pattern in the URLs here - after an _ character, the identifying size is shown eg ..._1280.png and ..._500.png 网址中有一个模式_字符后会显示识别大小,例如..._1280.png..._500.png

Would the best way to get these be to write a getter property that just appends a list of known sizes to a URL? 获取这些的最好方法是编写一个getter属性,该属性将一个已知大小的列表附加到URL上吗? Would this way be any less/more efficient than using purely the JSON.net converters? 与仅使用JSON.net转换器相比,这种方法会效率更低/更有效吗?

I suggest to parse your JSON into a dictionary first, as described here , and then manually copy it to a more structured object: 我建议你首先JSON解析成一个字典,如所描述这里 ,然后手动将其复制到一个更有条理的对象:

Dictionary<string, string> dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
var myImageObject = new { Id = "", Images = new Dictionary<int, string>()};
foreach(var key in dict.Keys) {
    if(key == "id") {
         myImageObject.Id = dict[key]
    }
    else {
         var imageSize = ParseForImageSize(key);
         myImageObject.Images.Add(imageSize, dict[key])
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM