Last active
November 2, 2019 08:02
-
-
Save yubeneko/8bc27383e7429f54346f3addd6296fe2 to your computer and use it in GitHub Desktop.
UnityでのJsonのデシリアライズその1
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 System; | |
using System.Collections.Generic; | |
using System.Globalization; | |
using System.Linq; | |
using Newtonsoft.Json.Linq; | |
using UnityEngine; | |
public class JsonDeserializeTest1 : MonoBehaviour | |
{ | |
string jsonText = ""; | |
string pattern = "yyyy-MM-dd HH:mm"; | |
List<DateTime> dateTimes; | |
void Start () | |
{ | |
TextAsset textasset = new TextAsset (); | |
textasset = Resources.Load ("TestJsonData", typeof (TextAsset)) as TextAsset; | |
jsonText = textasset.text; | |
JsonDeserializeWithJsonDotNET (); | |
// JsonDeserializeWithJsonUtility (); | |
} | |
void JsonDeserializeWithJsonDotNET () | |
{ | |
JObject jo = JObject.Parse (jsonText); | |
List<string> dateTimeStrings = jo["type1"]["times"].Children () | |
.Select (x => x.ToString ()) | |
.ToList (); | |
dateTimes = CreateDateTimeList (dateTimeStrings); | |
} | |
void JsonDeserializeWithJsonUtility () | |
{ | |
Item item = JsonUtility.FromJson<Item> (jsonText); | |
dateTimes = CreateDateTimeList (item.type1.times); | |
} | |
List<DateTime> CreateDateTimeList (List<string> dateTimeStrings) | |
{ | |
var dateTimes = new List<DateTime> (); | |
foreach (var dts in dateTimeStrings) | |
{ | |
if (DateTime.TryParseExact (dts, pattern, null, | |
DateTimeStyles.AssumeLocal, out DateTime parsedDate)) | |
{ | |
dateTimes.Add (parsedDate); | |
} | |
else | |
{ | |
Debug.LogError ($"Unable to convert '{dts}' to a date and time."); | |
} | |
} | |
return dateTimes; | |
} | |
[Serializable] | |
public class Item | |
{ | |
public Type type1; | |
} | |
[Serializable] | |
public class Type | |
{ | |
public List<string> times; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment