質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Xamarin

Xamarin(ザマリン)は、iPhoneなどのiOSやAndroidで動作し、C# 言語を用いてアプリを開発できるクロスプラットフォーム開発環境です。Xamarin Studioと C# 言語を用いて、 iOS と Android の両方の開発を行うことができます。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

2回答

11956閲覧

C#でJSONをデシアライズできない(Newtonsoft.JSON)

CoreiNion

総合スコア5

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Xamarin

Xamarin(ザマリン)は、iPhoneなどのiOSやAndroidで動作し、C# 言語を用いてアプリを開発できるクロスプラットフォーム開発環境です。Xamarin Studioと C# 言語を用いて、 iOS と Android の両方の開発を行うことができます。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2019/10/07 08:25

編集2019/10/07 09:41

Newtonsoft.Jsonを使ってJSONをデシアライズしようとしてますが、上手くできません。
ビルドはうまくいきますが、以下の例外エラーが出てしまいます。
JSONの読み込みは上手くできています。

**Newtonsoft.Json.JsonSerializationException:** 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[BEStatus.ShopItem]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'error', line 1, position 9.'

JSONに変換する部分はこのように書きました。

C#

1using System; 2using System.Collections.Generic; 3using System.Diagnostics; 4using System.Text; 5using System.Net.Http; 6using Newtonsoft.Json; 7using System.Threading.Tasks; 8using System.Runtime.Serialization.Json; 9 10namespace BEStatus 11{ 12 class GetApiData 13 { 14 //API情報 15 public string Token = "(Token key)"; 16 public string Store_URL = "https://--"; 17 18 //アイテムショップの処理 19 public List<ShopItem> ShopList; 20 public async Task<List<ShopItem>> ShopItemAsync() 21 { 22 //List作成 23 ShopList = new List<ShopItem>(); 24 HttpClient httpClient = new HttpClient(); 25 httpClient.DefaultRequestHeaders.Add("Authorization", Token); 26 //非同期でAPI取得 27 Task<string> stringAsync = httpClient.GetStringAsync(Store_URL); 28 string result = await stringAsync; 29 Debug.WriteLine(result); 30 //Jsonに変換 31 ShopList = JsonConvert.DeserializeObject<List<ShopItem>>(result); 32 //Listでreturn 33 return ShopList; 34 35 } 36 } 37 38 39 public class ShopImages 40 { 41 public string icon { get; set; } 42 public string background { get; set; } 43 public string featured { get; set; } 44 public string fbackground { get; set; } 45 } 46 47 public class ShopItem 48 { 49 public string name { get; set; } 50 public string rarity { get; set; } 51 public string type { get; set; } 52 public ShopImages images { get; set; } 53 } 54 55 public class ShopStore 56 { 57 public int cost { get; set; } 58 public int regularCost { get; set; } 59 public bool isFeatured { get; set; } 60 public bool isNew { get; set; } 61 public bool isCommunityVote { get; set; } 62 } 63 64 public class ShopDatum 65 { 66 public string itemId { get; set; } 67 public ShopItem item { get; set; } 68 public ShopStore store { get; set; } 69 } 70 71 public class ShopRootObject 72 { 73 public List<ShopDatum> data { get; set; } 74 public int updateAt { get; set; } 75 } 76}

下のコードはリストを表示させるためのコードです(Xamarin)

C#

1using System; 2using System.Collections.Generic; 3using System.Net.Http; 4using Newtonsoft.Json; 5using System.Threading.Tasks; 6using System.Runtime.Serialization.Json; 7using System.Text; 8using Xamarin.Forms; 9using Xamarin.Forms.Xaml; 10 11namespace BEStatus 12{ 13 [XamlCompilation(XamlCompilationOptions.Compile)] 14 public partial class TodayItemShop : ContentPage 15 { 16 17 public ListView listView; 18 public List<ShopItem> ShopList; 19 20 public TodayItemShop() 21 { 22 //リストのデザイン系 23 InitializeComponent(); 24 25 listView = new ListView 26 { 27 RowHeight = 60 28 }; 29 Content = new StackLayout 30 { 31 VerticalOptions = LayoutOptions.FillAndExpand, 32 Children = { listView } 33 }; 34 35 fetchArticles(new GetApiData()); 36 } 37 38 //非同期でデータ取得 39 async void fetchArticles(GetApiData Api) 40 { 41 42 ShopList = await Api.ShopItemAsync(); 43 var items = new List<String>(); 44 foreach (ShopItem value in ShopList) 45 { 46 items.Add(value.name); 47 } 48 listView.ItemsSource = items; 49 } 50 } 51} 52

読み込むJSONの文字列はこんな感じです。

JSON

1{ 2 "data": [ 3 { 4 "itemId": "ID", 5 "item": { 6 "name": "Sunrise", 7 "rarity": "rare", 8 "type": "glider", 9 "images": { 10 "icon": "URL", 11 "background": "URL", 12 "featured": "URL", 13 "fbackground": "URL" 14 } 15 }, 16 "store": { 17 "cost": 800, 18 "regularCost": 800, 19 "isFeatured": true, 20 "isNew": false, 21 "isCommunityVote": false 22 } 23 }, 24 { 25 "itemId": "ID", 26 "item": { 27 "name": "Sky Stripe", 28 "rarity": "uncommon", 29 "type": "glider", 30 "images": { 31 "icon": "URL", 32 "background": "URL", 33 "featured": "URL", 34 "fbackground": "URL" 35 } 36 }, 37 "store": { 38 "cost": 500, 39 "regularCost": 500, 40 "isFeatured": true, 41 "isNew": false, 42 "isCommunityVote": false 43 } 44 }, 45 { 46 "itemId": "ID", 47 "item": { 48 "name": "Axetec", 49 "rarity": "rare", 50 "type": "pickaxe", 51 "images": { 52 "icon": "URL", 53 "background": "URL", 54 "featured": "URL", 55 "fbackground": "URL" 56 } 57 }, 58 "store": { 59 "cost": 800, 60 "regularCost": 800, 61 "isFeatured": true, 62 "isNew": false, 63 "isCommunityVote": false 64 } 65 }, 66 { 67 "itemId": "ID", 68 "item": { 69 "name": "Stripe Slicer", 70 "rarity": "uncommon", 71 "type": "pickaxe", 72 "images": { 73 "icon": "URL", 74 "background": "URL", 75 "featured": "URL", 76 "fbackground": "URL" 77 } 78 }, 79 "store": { 80 "cost": 500, 81 "regularCost": 500, 82 "isFeatured": true, 83 "isNew": false, 84 "isCommunityVote": false 85 } 86 }, 87 { 88 "itemId": "ID", 89 "item": { 90 "name": "Iron Beak", 91 "rarity": "rare", 92 "type": "pickaxe", 93 "images": { 94 "icon": "URL", 95 "background": "URL", 96 "featured": "URL", 97 "fbackground": "URL" 98 } 99 }, 100 "store": { 101 "cost": 800, 102 "regularCost": 800, 103 "isFeatured": true, 104 "isNew": false, 105 "isCommunityVote": false 106 } 107 108 109 } 110 ], 111 "updateAt": 1570406481 112}

JSONはあまり触ったことがないので初歩的な質問かもしれませんが、回答よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

YAmaGNZ

2019/10/07 08:29 編集

ShopItemはどのように定義しているのですか? JSON側もせめて1つのデータ分は記載できないのでしょうか?
CoreiNion

2019/10/07 09:42

修正しました。
guest

回答2

0

ベストアンサー

提示されているJSONをクラスとして定義したものがShopRootObjectクラス等でここまでは合っています。
ただ、デシリアライズする型がShopRootObjectクラスではなくList<ShopItem>としています。
この為、入力のJSONと型が合わずにエラーとなっています。

投稿2019/10/07 10:09

YAmaGNZ

総合スコア10222

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

resultに格納されるJSON文字列はShopRootObjectクラスの形式なので
ShopList = JsonConvert.DeserializeObject<List<ShopItem>>(result);
の部分を
ShopList = JsonConvert.DeserializeObject<ShopRootObject>(result);
に変更すれば通ると思います。

投稿2019/10/07 13:06

tsubaki961

総合スコア73

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問