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

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

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

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

JSON

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

Unity

Unityは、Unity Technologiesが開発・販売している、IDEを内蔵するゲームエンジンです。主にC#を用いたプログラミングでコンテンツの開発が可能です。

Q&A

2回答

1968閲覧

unity(C#)でjson取得したデーター[ { { 個々 } } ] のデーターを取得したい

nitiyoubi

総合スコア10

C#

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

JSON

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

Unity

Unityは、Unity Technologiesが開発・販売している、IDEを内蔵するゲームエンジンです。主にC#を用いたプログラミングでコンテンツの開発が可能です。

0グッド

0クリップ

投稿2019/02/21 03:33

編集2019/02/28 02:04

以下のコードが前提となるデーターです。

json

1{ 2   "forecasts": [ 3        { 4            "dateLabel": "明日", 5            "telop": "曇のち雨", 6            "date": "2019-02-22", 7            "temperature": { 8                "min": { 9                    "celsius": "5", 10                    "fahrenheit": "41.0" 11                }, 12                "max": { 13                    "celsius": "14", 14                    "fahrenheit": "57.2" 15                } 16            }, 17            "image": { 18                "width": 50, 19                "url": "http://weather.livedoor.com/img/icon/13.gif", 20                "title": "曇のち雨", 21                "height": 31 22            } 23        }, 24    ], 25}

この中のtemperatureの中のminの中のfahrenheitが取得したいのですがどうしても取得できませんでした。やり方を知っていたら教えて下さい、よろしくお願いします。

追記
自分が書いていたコードです

c#

1using System; 2using System.Collections; 3using System.Collections.Generic; 4using System.Text; 5using UnityEngine; 6using UnityEngine.Events; 7using UnityEngine.UI; 8using MiniJSON; 9using JsonData; 10 11public class WeatherAPI_test1 : MonoBehaviour 12{ 13 14 static public string url = "http://weather.livedoor.com/forecast/webservice/json/v1?city=400040";//天気URL 15 16 string advis; 17 string image; 18 19 void Start() 20 { 21 22 StartCoroutine("connectdata"); 23 } 24 25 private IEnumerator connectdata() 26 { 27 WWW www = new WWW(url); 28 yield return www; 29 if (!string.IsNullOrEmpty(www.error)) 30 { 31 32 print("Error downloading: " + www.error); 33 34 } 35 else 36 { 37 38 string jsonText = www.text;//受け取ったデーターをjsonTextにIN 39 40 JsonDataClass jsonDataClass; 41 JsonDataClas_image jsonDataClas_image; 42 43 jsonDataClass = JsonUtility.FromJson<JsonDataClass>(jsonText); 44 45 46 Debug.Log(jsonText); 47 48 var json = jsonText; 49 //(1階層目) 50 var jsonData = MiniJSON.Json.Deserialize(json) as Dictionary<string, object>;//全体の並列取得 51 //(2階層目) 52 var description = jsonData["description"] as Dictionary<string, object>;//天気概況文の配列 53 var forecasts = (IList)jsonData["forecasts"];//府県天気予報の予報日毎の配列 54 var pinpointLocations = (IList)jsonData["pinpointLocations"];//ピンポイント予報の発表地点の配列 55 var location = jsonData["location"] as Dictionary<string, object>;//予報を発表した地域を定義 56 57 58 59 60 61 //(3階層目) 62 var forecasts_0 = (IDictionary)forecasts[0]; 63 var forecasts_1 = (IDictionary)forecasts[1]; 64 var forecasts_2 = (IDictionary)forecasts[2]; 65 66 67 68 var pinpointLocations_0 = (IDictionary)pinpointLocations[0]; 69 var pinpointLocations_1 = (IDictionary)pinpointLocations[1]; 70 var pinpointLocations_2 = (IDictionary)pinpointLocations[2]; 71 var pinpointLocations_3 = (IDictionary)pinpointLocations[3]; 72 var pinpointLocations_4 = (IDictionary)pinpointLocations[4]; 73 var pinpointLocations_5 = (IDictionary)pinpointLocations[5]; 74 var pinpointLocations_6 = (IDictionary)pinpointLocations[6]; 75 var pinpointLocations_7 = (IDictionary)pinpointLocations[7]; 76 77 78 79 Debug.Log(jsonDataClass.title); 80 OUTPutUI_script.title = jsonDataClass.title; 81 82 advis = (string)description["text"]; 83 84 OUTPutUI_script.advice = advis.Replace("\n", ""); 85 86 OUTPutUI_script.today_dateLabel = (string)forecasts_0["dateLabel"]; 87 OUTPutUI_script.today_weather = (string)forecasts_0["telop"]; 88 OUTPutUI_script.today_date = (string)forecasts_0["date"]; 89 90 OUTPutUI_script.tomorrow_dateLabel = (string)forecasts_1["dateLabel"]; 91 OUTPutUI_script.tomorrow_weather = (string)forecasts_1["telop"]; 92 OUTPutUI_script.tomorrow_date = (string)forecasts_1["date"]; 93 94 OUTPutUI_script.afterTomorrow_dateLabel = (string)forecasts_2["dateLabel"]; 95 OUTPutUI_script.afterTomorrow_weather = (string)forecasts_2["telop"]; 96 OUTPutUI_script.afterTomorrow_date = (string)forecasts_2["date"]; 97 98 Debug.Log((string)forecasts_0["dateLabel"]);//予報日(今日、明日、明後日のいずれか) 99 Debug.Log((string)forecasts_0["telop"]);//天気 100 Debug.Log((string)forecasts_0["date"]);//予報日 101 102 Debug.Log((string)forecasts_1["dateLabel"]);//予報日(今日、明日、明後日のいずれか) 103 Debug.Log((string)forecasts_1["telop"]);//天気 104 Debug.Log((string)forecasts_1["date"]);//予報日 105 106 107 108 // Debug.Log((string)forecasts_2["dateLabel"]);//予報日(今日、明日、明後日のいずれか) 109 // Debug.Log((string)forecasts_2["telop"]);//天気 110 // Debug.Log((string)forecasts_2["date"]);//予報日 111 112 Debug.Log((string)pinpointLocations_0["link"]);//リンク 113 Debug.Log((string)pinpointLocations_0["name"]);//リンク 114 Debug.Log((string)pinpointLocations_1["link"]);//リンク 115 Debug.Log((string)pinpointLocations_1["name"]);//リンク 116 117 Debug.Log((string)description["text"]);//天気概況本文 118 Debug.Log((string)description["publicTime"]);//天気概況文の発表時刻 119 120 121 122 // Debug.Log((double)location["city"]);//都市 123 Debug.Log((string)location["area"]);//地方名(例・九州地方) 124 Debug.Log((string)location["prefecture"]);//都道府県名(例・福岡県) 125 Debug.Log((string)location["city"]);//1次細分区名(例・八幡) 126 127 128 129 // Debug.Log((double)main["temp_max"]);//最高気温 130 // Debug.Log((double)coord["lon"]);//経度 131 // Debug.Log((double)main["pressure"]);//気圧 132 // Debug.Log((long)main["humidity"]);//湿度 133 // Debug.Log((double)wind["speed"]);//風速 134 // Debug.Log((string)jsonData["name"]);//都市名 135 // Debug.Log((string)sys["country"]);//国名 136 // Debug.Log((long)sys["sunrise"]);//日の出時間 137 // Debug.Log((long)sys["sunset"]);//日没時間 138 139 140 } 141 } 142} 143namespace JsonData 144{ 145 public class JsonDataClass 146 { 147 148 public string publicTime;//予報の発表日時 149 150 public string title;//タイトル・見出し 151 152 public string link; 153 154 public string telop; 155 156 } 157 public class JsonDataClas_image 158 { 159 public string image; 160 } 161}

でデーターを取得して

c#

1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4using UnityEngine.UI; 5 6public class OUTPutUI_script : MonoBehaviour 7{ 8 9 static public string title; 10 11 static public string advice; 12 13 static public string img; 14 15 static public string today_weather; 16 static public string today_date; 17 static public string today_dateLabel; 18 19 static public string tomorrow_weather; 20 static public string tomorrow_date; 21 static public string tomorrow_dateLabel; 22 23 static public string afterTomorrow_weather; 24 static public string afterTomorrow_date; 25 static public string afterTomorrow_dateLabel; 26 27 public Text Title; 28 29 public Text Advice; 30 31 public Text Today_weather; 32 public Text Today_date; 33 public Text Today_dateLabel; 34 35 public Text Tomorrow_weather; 36 public Text Tomorrow_dat; 37 public Text Tomorrow_dateLabel; 38 39 public Text AfterTomorrow_weather; 40 public Text AfterTomorrow_dat; 41 public Text AfterTomorrow_dateLabe; 42 43 // Start is called before the first frame update 44 void Start() 45 { 46 47 } 48 49 // Update is called once per frame 50 void Update() 51 { 52 53 if (System_script.switch_jg == "1") 54 { 55 SwitchON(); 56 } 57 58 } 59 public void SwitchON() 60 { 61 Title.text = title; 62 63 Advice.text = advice; 64 65 Today_date.text = today_date; 66 Today_weather.text = today_weather; 67 Today_dateLabel.text = today_dateLabel; 68 69 Tomorrow_dat.text = tomorrow_date; 70 Tomorrow_weather.text = tomorrow_weather; 71 Tomorrow_dateLabel.text = tomorrow_dateLabel; 72 73 AfterTomorrow_dat.text = afterTomorrow_date; 74 AfterTomorrow_weather.text = afterTomorrow_weather; 75 AfterTomorrow_dateLabe.text = afterTomorrow_dateLabel; 76 } 77} 78

で出力しています
上のjsonデーターは取得したデーターの中の自分が取り出せなくて困っている部分だけを書き出した物です。

追記遅くなってしまってごめんなさい。

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

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

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

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

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

BluOxy

2019/02/21 03:44

>どうしても取得できませんでした。 試したこと(例えば、JSONで取得しようとして動かなかったコードや使用したライブラリ)を載せてください。
guest

回答2

0

C#でJsonを取り扱うのであれば、Json.NET等のライブラリを使うことが基本的に多いと思います。
環境を準備するために以下の手順が必要になります。
0. http://www.newtonsoft.com/jsonへ行って、zipをダウンロード
0. zipファイルを解凍して「Bin\Net20\Newtonsoft.json.dll」をUnityのPluginsフォルダにコピー

準備が出来次第、次の手順を行います。
0. Jsonに対応するオブジェクトの定義
0. Json-オブジェクト間の変換(シリアライズ・デシリアライズ)を行い取得したデータにアクセスする

詳細については以下に記載しますので、ご参考にしてください。

Json.NETで提示されたJsonコードを取り扱う場合は、Jsonの構造に合わせてクラスの定義を行います。
(json2csharpというサイトでクラス定義に変換しました)

C#

1public class Min 2{ 3 public string celsius { get; set; } 4 public string fahrenheit { get; set; } 5} 6 7public class Max 8{ 9 public string celsius { get; set; } 10 public string fahrenheit { get; set; } 11} 12 13public class Temperature 14{ 15 public Min min { get; set; } 16 public Max max { get; set; } 17} 18 19public class Image 20{ 21 public int width { get; set; } 22 public string url { get; set; } 23 public string title { get; set; } 24 public int height { get; set; } 25} 26 27public class Forecast 28{ 29 public string dateLabel { get; set; } 30 public string telop { get; set; } 31 public string date { get; set; } 32 public Temperature temperature { get; set; } 33 public Image image { get; set; } 34} 35 36public class RootObject 37{ 38 public List<Forecast> forecasts { get; set; } 39}

あとはJsonをForecastまたはRootObjectクラスのインスタンスとして取り込み、メンバーにアクセスすれば良いです。インスタンスとして取り込むことをデシリアライズって言います。

コード例は次になります。

C#

1public void Hoge(){ 2 using (var sr = new StreamReader(jsonファイルのパス, Encoding.UTF8)) 3 { 4 var data = sr.ReadToEnd(); 5 var obj = JsonConvert.DeserializeObject<RootObject>(data); 6 7 //temperatureの中のminの中のfahrenheitを取得 8 Console.WriteLine(obj.forecasts.First().temperature.min.fahrenheit); 9 } 10}

参考:UnityでJson.NETを使う
他のライブラリ:[C#] C#でJSONを扱う方法まとめ

投稿2019/02/21 03:48

編集2019/02/25 02:47
BluOxy

総合スコア2663

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

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

0

最初に

追記を見ました。
趣旨が変わるので別途こちらで回答します。

次にご質問する際はお互いの問答が円滑に行えるよう、ご自身でされたことを事前に書くようにしてください。
先の回答のようにnitiyoubiさんの求めている内容からはどうしても離れてしまいますから。

回答+気になる点

全体的な実装で気になった点が変数名に数字をつけるのではなく、foreachでコレクションの全てを列挙するべきです。

もしforecastsの要素数が増えて、例えば5つ目の部分が欲しいとなった場合、その都度forecasts_4などと変数を追加しなければいけなくなります。

同じコードを書いているな、と思ったら書かないよう色々考えてみるとコードが物凄く減り、見やすく管理しやすいコードになります。DRYの法則で調べてみると良いでしょう。

その点を踏まえてminfahreheitにアクセスする方法を、nitiyoubiさんが添付されたコードを改造して作りました。既存の動きとほぼ似たような振る舞いをするはずです。

なお、実際に動作確認はしていないため何も考えずに流用はせず、参考程度に見てください。
(つまり、流用された際に発生した細かいコンパイルエラーはお手数ですが自分で直してください、自分はコード代行屋ではないので)

WeatherAPI_test1 の実装

C#

1using System; 2using System.Collections; 3using System.Collections.Generic; 4using System.Text; 5using UnityEngine; 6using UnityEngine.Events; 7using UnityEngine.UI; 8using MiniJSON; 9using JsonData; 10 11public class WeatherAPI_test1 : MonoBehaviour 12{ 13 14 static public string url = "http://weather.livedoor.com/forecast/webservice/json/v1?city=400040";//天気URL 15 16 string advis; 17 string image; 18 19 void Start() 20 { 21 22 StartCoroutine("connectdata"); 23 } 24 25 26 private IEnumerator connectdata() 27 { 28 WWW www = new WWW(url); 29 yield return www; 30 if (!string.IsNullOrEmpty(www.error)) 31 { 32 33 print("Error downloading: " + www.error); 34 35 } 36 else 37 { 38 39 string jsonText = www.text;//受け取ったデーターをjsonTextにIN 40 Debug.Log(jsonText); 41 42 var json = jsonText; 43 //(1階層目) 44 var jsonData = MiniJSON.Json.Deserialize(json) as Dictionary<string, object>;//全体の並列取得 45 //(2階層目) 46 var description = jsonData["description"] as Dictionary<string, object>;//天気概況文の配列 47 var forecasts = (IList)jsonData["forecasts"];//府県天気予報の予報日毎の配列 48 var pinpointLocations = (IList)jsonData["pinpointLocations"];//ピンポイント予報の発表地点の配列 49 var location = jsonData["location"] as Dictionary<string, object>;//予報を発表した地域を定義 50 51 foreach(var forecast in forecasts.Cast<IDictionary>().Select((item, index)=> new { item, index}){ 52 OUTPutUI_script.dateLabel[(DateTimeTypes)forecast.index] = (string)forecast.item["dateLabel"]; 53 OUTPutUI_script.weather[(DateTimeTypes)forecast.index] = (string)forecast.item["telop"]; 54 OUTPutUI_script.date[(DateTimeTypes)forecast.index] = (string)forecast.item["date"]; 55 56 var temprature = (IDictionary)forecast["temperature"]; 57 var min = (IDictionary)temprature["min"]; 58 59 //nitiyoubiさんの求めているもの 60 Console.Log(min["fahreheit"]); 61 62 Debug.Log((string)forecast.item["dateLabel"]);//予報日(今日、明日、明後日のいずれか) 63 Debug.Log((string)forecast.item["telop"]);//天気 64 Debug.Log((string)forecast.item["date"]);//予報日 65 } 66 67 foreach(var pinpointLocation in pinpointLocations.Cast<IDictionary>()){ 68 /* 69 このループの中で以下の処理と同等のことができるので、 70 変数名を「変数+数字」の形式にしなくて良い。 71 var pinpointLocations_0 = (IDictionary)pinpointLocations[0]; 72 var pinpointLocations_1 = (IDictionary)pinpointLocations[1]; 73 var pinpointLocations_2 = (IDictionary)pinpointLocations[2]; 74 ・・・ 75 */ 76 Debug.Log((string)pinpointLocation["link"]);//リンク 77 Debug.Log((string)pinpointLocation["name"]);//名前 78 79 } 80 81 Debug.Log(jsonDataClass.title); 82 OUTPutUI_script.title = jsonDataClass.title; 83 84 advis = (string)description["text"]; 85 86 OUTPutUI_script.advice = advis.Replace("\n", ""); 87 88 Debug.Log((string)description["text"]);//天気概況本文 89 Debug.Log((string)description["publicTime"]);//天気概況文の発表時刻 90 Debug.Log((string)location["area"]);//地方名(例・九州地方) 91 Debug.Log((string)location["prefecture"]);//都道府県名(例・福岡県) 92 Debug.Log((string)location["city"]);//1次細分区名(例・八幡) 93 } 94 } 95}

OUTPutUI_scriptの実装

C#

1public class OUTPutUI_script : MonoBehaviour 2{ 3 4 static public string title; 5 static public string advice; 6 static public string img; 7 8 public static Dictionary<DateTimeTypes,string> weather; 9 public static Dictionary<DateTimeTypes,string> date; 10 public static Dictionary<DateTimeTypes,string> dateLabel; 11 12 public Text Title; 13 public Text Advice; 14 15 public Text Today_weather; 16 public Text Today_date; 17 public Text Today_dateLabel; 18 19 public Text Tomorrow_weather; 20 public Text Tomorrow_dat; 21 public Text Tomorrow_dateLabel; 22 23 public Text AfterTomorrow_weather; 24 public Text AfterTomorrow_dat; 25 public Text AfterTomorrow_dateLabe; 26 27 // Start is called before the first frame update 28 void Start() 29 { 30 31 } 32 33 // Update is called once per frame 34 void Update() 35 { 36 37 if (System_script.switch_jg == "1") 38 { 39 SwitchON(); 40 } 41 42 } 43 public void SwitchON() 44 { 45 Title.text = title; 46 47 Advice.text = advice; 48 49 Today_date.text = date[DateTimeTypes.Today]; 50 Today_weather.text = weather[DateTimeTypes.Today]; 51 Today_dateLabel.text = dateLabel[DateTimeTypes.Today]; 52 53 Tomorrow_dat.text = date[DateTimeTypes.Tomorrow]; 54 Tomorrow_weather.text = weather[DateTimeTypes.Tomorrow]; 55 Tomorrow_dateLabel.text = dateLabel[DateTimeTypes.Tomorrow]; 56 57 AfterTomorrow_dat.text = date[DateTimeTypes.AfterTomorrow]; 58 AfterTomorrow_weather.text = weather[DateTimeTypes.AfterTomorrow]; 59 AfterTomorrow_dateLabe.text = dateLabel[DateTimeTypes.AfterTomorrow]; 60 } 61} 62 63public enum DateTimeTypes{, 64 Today = 0, 65 Tomorrow = 1, 66 AfterTomorrow = 2, 67}

投稿2019/02/28 04:23

編集2019/02/28 04:34
BluOxy

総合スコア2663

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問