1

ネットC#。WebサービスからJsonを解析しようとしています。テキストで実行しましたが、画像の解析に問題があります。これが私がJsonを取得しているURLです

http://collectionking.com/rest/view/items_in_collection.json?args=122

そしてこれはそれを解析するための私のコードです

using (var wc = new WebClient()) {
JavaScriptSerializer js = new JavaScriptSerializer();
var result = js.Deserialize<ck[]>(wc.DownloadString("http://collectionking.com/rest/view/items_in_collection.json args=122"));
foreach (var i in result) {
lblTitle.Text = i.node_title;
imgCk.ImageUrl = i.["main image"];
lblNid.Text = i.nid;

どんな助けでも素晴らしいでしょう。前もって感謝します。PS:タイトルとNidは返しますが、画像は返しません。私のクラスは次のとおりです。

public class ck
{    
public string node_title;
public string main_image;
public string nid;  }
4

2 に答える 2

2

問題は、ImageUrlを<img typeof="foaf:Image" src="http://...実際のURLではなくこのようなものに設定していることです。main image正しく表示するには、URLをさらに解析して抽出する必要があります。

編集

これは、空白のためにひびが入るのは難しいことでした。私が見つけた唯一の解決策は、文字列を解析する前に空白を削除することでした。これはあまり良い解決策ではありませんが、組み込みのクラスを使用する他の方法を見つけることができませんでした。ただし、 JSON.Netまたはその他のライブラリを使用して適切に解決できる場合があります。

また、URLを抽出するための正規表現を追加しましたが、ここで何をチェックしてもエラーは発生しないため、自分で追加する必要があります。

using (var wc = new WebClient()) {
    JavaScriptSerializer js = new JavaScriptSerializer();
    var result = js.Deserialize<ck[]>(wc.DownloadString("http://collectionking.com/rest/view/items_in_collection.json?args=122").Replace("\"main image\":", "\"main_image\":")); // Replace the name "main image" with "main_image" to deserialize it properly, also fixed missing ? in url
    foreach (var i in result) {
        lblTitle.Text = i.node_title;
        string realImageUrl = Regex.Match(i.main_image, @"src=""(.*?)""").Groups[1].Value;  // Extract the value of the src-attribute to get the actual url, will throw an exception if there isn't a src-attribute
        imgCk.ImageUrl = realImageUrl;
        lblNid.Text = i.nid;
    }
}
于 2012-12-22T08:24:16.083 に答える
1

これを試して

 private static string ExtractImageFromTag(string tag)
 {
 int start = tag.IndexOf("src=\""),
    end = tag.IndexOf("\"", start + 6);
return tag.Substring(start + 5, end - start - 5);
}
private static string ExtractTitleFromTag(string tag)
{
int start = tag.IndexOf(">"),
    end = tag.IndexOf("<", start + 1);
return tag.Substring(start + 1, end - start - 1);
}

それは役立つかもしれません

于 2012-12-22T13:02:31.033 に答える