Last active
June 23, 2017 11:28
-
-
Save muzudho/ded1aee5942239548fbe0290f706eb19 to your computer and use it in GitHub Desktop.
UnityでJSONを読み書きしようぜ(特にDictionaryで) ref: http://qiita.com/muzudho1/items/26bda7d5e3c8dfac304c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
[System.Serializable] | |
public class PlayerInfo | |
{ | |
public string name; | |
public int lives; | |
public float health; | |
public static PlayerInfo CreateFromJSON(string jsonString) | |
{ | |
return JsonUtility.FromJson<PlayerInfo>(jsonString); | |
} | |
// Given JSON input: | |
// {"name":"Dr Charles","lives":3,"health":0.8} | |
// this example will return a PlayerInfo object with | |
// name == "Dr Charles", lives == 3, and health == 0.8f. | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEditor; | |
using UnityEngine; | |
public class ToolMenu { | |
#region JSONの動作テスト | |
[MenuItem("Tool/Json Test")] | |
static void JsonTest() | |
{ | |
PlayerInfo pi = PlayerInfo.CreateFromJSON("{\"name\":\"Dr Charles\", \"lives\":3,\"health\":0.8}"); | |
Debug.Log("pi.name = " + pi.name); | |
Debug.Log("pi.lives = " + pi.lives); | |
Debug.Log("pi.health = " + pi.health); | |
} | |
#endregion | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dictionary<string, object> dic |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dictionary<string, object> dic1 = Json.Deserialize(sampleJson) as Dictionary<string, object>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
foreach (KeyValuePair<string, object> entry in dic) | |
{ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
switch (entry.Key) | |
{ | |
case "number": obj.number = (long)entry.Value; break; | |
case "text": obj.text = (string)entry.Value; break; | |
case "properties": | |
// 略 | |
break; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
foreach (KeyValuePair<string, object> entry in dic) | |
{ | |
switch (entry.Key) | |
{ | |
case "layers": ParseArray1((List<object>)entry.Value, obj); break; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void ParseLayers(List<object> array, MiniJSONObject obj) | |
{ | |
foreach (Dictionary<string,object> dic in array) | |
{ | |
switch ((string)dic["name"]) | |
{ | |
case "Apple": | |
Debug.Log("りんご"); | |
break; | |
case "Banana": | |
Debug.Log("ばなな"); | |
break; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Debug.Log("groundの型=" + ground.GetType().Name); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
foreach (object element in (List<object>)dic["data"]) | |
{ | |
obj.arrayData.Add((int)((long)element)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
※前略 | |
"tileproperties": | |
{ | |
"32": | |
{ | |
"Collision":true | |
}, | |
"33": | |
{ | |
"Collision":true | |
}, | |
"34": | |
{ | |
"Collision":true | |
}, | |
"35": | |
{ | |
"Collision":true | |
} | |
}, | |
※後略 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"32": | |
{ | |
"Collision":true | |
}, | |
"33": | |
{ | |
"Collision":true | |
}, | |
"34": | |
{ | |
"Collision":true | |
}, | |
"35": | |
{ | |
"Collision":true | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"keys":[1000,2000], | |
"values":[ | |
{"name":"スライム","skills":["攻撃"]}, | |
{"name":"キングスライム","skills":["攻撃","回復"]} | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[MenuItem("Tool/Json Test Tileproperties MiniJSON")] | |
static void JsonTestTilepropertiesMiniJSON() | |
{ | |
string jsonString = | |
@" | |
{ | |
""32"": | |
{ | |
""collision"":true | |
}, | |
""33"": | |
{ | |
""collision"":true | |
}, | |
""34"": | |
{ | |
""collision"":true | |
}, | |
""35"": | |
{ | |
""collision"":true | |
} | |
} | |
" | |
; | |
Dictionary<string, object> dict = Json.Deserialize(jsonString) as Dictionary<string, object>; | |
Debug.Log("deserialized: " + dict.GetType()); | |
Debug.Log("dict['32']['collision']: " + ((Dictionary<string, object>)dict["32"])["collision"]); | |
Debug.Log("dict['33']['collision']: " + ((Dictionary<string, object>)dict["33"])["collision"]); | |
Debug.Log("dict['34']['collision']: " + ((Dictionary<string, object>)dict["34"])["collision"]); | |
Debug.Log("dict['35']['collision']: " + ((Dictionary<string, object>)dict["35"])["collision"]); | |
var str = Json.Serialize(dict); | |
Debug.Log("serialized: " + str); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MiniJSON; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using NUnit.Framework; | |
using System.Text; | |
/// <summary> | |
/// MiniJSON の使用例 | |
/// </summary> | |
class MiniJsonTest | |
{ | |
/// <summary> | |
/// Unityエディターのメインメニュー [Window] - [Test Runner] - [Run All] で単体テスト。 | |
/// </summary> | |
[Test] | |
public static void TestMiniJson_SampleJson1() | |
{ | |
object obj = Json.Deserialize( | |
@"{""number"":32}" | |
); | |
Debug.Assert(null != obj); | |
} | |
[Test] | |
public static void TestMiniJson_SampleJson2() | |
{ | |
Dictionary<string, object> dic1 = Json.Deserialize( | |
@"{""number"":32}" | |
) as Dictionary<string, object>; | |
Debug.Assert(null != dic1); | |
} | |
const string sampleJson = | |
@" | |
{ | |
""number"":32, | |
""text"":""hello world"", | |
""properties"": | |
{ | |
""32"": | |
{ | |
""visible"":true | |
}, | |
""33"": | |
{ | |
""visible"":true | |
}, | |
""34"": | |
{ | |
""visible"":true | |
}, | |
""35"": | |
{ | |
""visible"":true | |
} | |
} | |
} | |
"; | |
[Test] | |
public static void TestMiniJson_SampleJson3() | |
{ | |
Dictionary<string, object> dic1 = Json.Deserialize(sampleJson) as Dictionary<string, object>; | |
Debug.Assert(null != dic1); | |
Debug.Assert(32 == (long)dic1["number"]); | |
Debug.Assert("hello world" == (string)dic1["text"]); | |
Debug.Assert(true == (bool)( | |
(Dictionary<string, object>) | |
((Dictionary<string, object>) | |
dic1["properties"] | |
)["32"] | |
)["visible"] | |
); | |
Debug.Assert(true == (bool)( | |
(Dictionary<string, object>) | |
((Dictionary<string, object>) | |
dic1["properties"] | |
)["33"] | |
)["visible"] | |
); | |
Debug.Assert(true == (bool)( | |
(Dictionary<string, object>) | |
((Dictionary<string, object>) | |
dic1["properties"] | |
)["34"] | |
)["visible"] | |
); | |
Debug.Assert(true == (bool)( | |
(Dictionary<string, object>) | |
((Dictionary<string, object>) | |
dic1["properties"] | |
)["35"] | |
)["visible"] | |
); | |
} | |
[Test] | |
public static void TestMiniJson_CreateFromJSON() | |
{ | |
MiniJsonObject obj = CreateFromJSON(sampleJson); | |
Debug.Assert(32 == obj.number); | |
Debug.Assert("hello world" == obj.text); | |
Debug.Assert(true == (bool)((Dictionary<string, object>)obj.properties["32"])["visible"]); | |
Debug.Assert(true == (bool)((Dictionary<string, object>)obj.properties["33"])["visible"]); | |
Debug.Assert(true == (bool)((Dictionary<string, object>)obj.properties["34"])["visible"]); | |
Debug.Assert(true == (bool)((Dictionary<string, object>)obj.properties["35"])["visible"]); | |
} | |
[Test] | |
public static void TestMiniJson_ToJSON() | |
{ | |
MiniJsonObject obj = CreateFromJSON(sampleJson); | |
// 空白を飛ばしたものと比較したいが、文字列の中の空白は飛ばしてはいけないので、むずかしい。 | |
// obj.ToJson()={"number":32,"text":"hello world","properties":{"32":{"visible":true},"33":{"visible":true},"34":{"visible":true},"35":{"visible":true}}} | |
// expect ={"number":32,"text":"helloworld","properties":{"32":{"visible":true},"33":{"visible":true},"34":{"visible":true},"35":{"visible":true}}} | |
string s = obj.ToJson(); | |
//string expect = sampleJson.Replace("\r", "").Replace("\n", "").Replace(" ", ""); | |
string expect = @"{""number"":32,""text"":""hello world"",""properties"":{""32"":{""visible"":true},""33"":{""visible"":true},""34"":{""visible"":true},""35"":{""visible"":true}}}"; | |
Debug.Assert(expect == s, "obj.ToJson()=" + s + " expect="+ expect); | |
} | |
public static MiniJsonObject CreateFromJSON(string jsonString) | |
{ | |
MiniJsonObject obj = new MiniJsonObject(); | |
Dictionary<string, object> firstDic = Json.Deserialize(jsonString) as Dictionary<string, object>; | |
foreach (KeyValuePair<string, object> firstEntry in firstDic) | |
{ | |
switch (firstEntry.Key) | |
{ | |
case "number": obj.number = (long)firstEntry.Value; break; | |
case "text": obj.text = (string)firstEntry.Value; break; | |
case "properties": | |
{ | |
Dictionary<string, object> propertiesDic = (Dictionary<string, object>)firstEntry.Value; | |
foreach (KeyValuePair<string, object> propertiesEntry in propertiesDic) | |
{ | |
Dictionary<string, object> customDic = (Dictionary<string, object>)propertiesEntry.Value; | |
foreach (KeyValuePair<string, object> customEntry in customDic) | |
{ | |
// チェックせずに丸ごと追加してもいいのでは。 | |
switch (customEntry.Key) | |
{ | |
case "visible": | |
obj.properties.Add(propertiesEntry.Key, customDic); | |
break; | |
} | |
} | |
} | |
} | |
break; | |
} | |
} | |
return obj; | |
} | |
public class MiniJsonObject | |
{ | |
/// <summary> | |
/// MiniJSONでは、数字は long型として扱う | |
/// </summary> | |
public long number; | |
public string text; | |
/// <summary> | |
/// MiniJSONでは、シンプルな構造に限り、連想配列も読取可能 | |
/// </summary> | |
[SerializeField] | |
public Dictionary<string, object> properties; | |
/// <summary> | |
/// Unit Test 用のデフォルト・コンストラクタ | |
/// </summary> | |
public MiniJsonObject() | |
{ | |
properties = new Dictionary<string, object>(); | |
} | |
public string ToJson() | |
{ | |
StringBuilder sb = new StringBuilder(); | |
sb.Append("{"); | |
sb.Append(@"""number"":");sb.Append(Json.Serialize(number)); | |
sb.Append(","); | |
sb.Append(@"""text"":"); sb.Append(Json.Serialize(text)); | |
sb.Append(","); | |
sb.Append(@"""properties"":"); sb.Append(Json.Serialize(properties)); | |
sb.Append("}"); | |
return sb.ToString(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dictionary<string, object> firstDic = Json.Deserialize(jsonString) as Dictionary<string, object>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MiniJSON; | |
using System.Collections.Generic; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MiniJsonObject | |
{ | |
public static MiniJsonObject CreateFromJSON(string jsonString) | |
{ | |
// ここにJSON読み取り処理を書く | |
} | |
// ここにデータ構造を作る | |
public string ToJson() | |
{ | |
// ここにJSON出力処理を書く | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment