facebook twitter hatena line email

「Unity/Csharp/Json/NewtonJson」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(サンプル)
(=unity2022以降)
 
(同じ利用者による、間の30版が非表示)
行1: 行1:
==NewtonJsonのdllをDL==
+
==NewtonJsonをDL&インストール==
#https://www.nuget.org/packages/Newtonsoft.Json をDLし、.nupkgを.zipに変更し、解凍。
+
===unity2022以降===
#lib\netstandard2.0の下のNewtonsoft.Json.dllをPluginsの下に設置
+
再度このライブラリは、入らなくなったっぽい。
 +
unityメニュー/Windows/PackageManagerを開いて、左上の+、Add package from git URLから、以下を入れてインストールする
 +
com.unity.nuget.newtonsoft-json
 +
 
 +
参考:https://qiita.com/T_keigo/items/ec6e864114697a846f70
 +
===unity2020.3.0f1以降では===
 +
最初から、Newtonsoft.Jsonが入ってる?ようで、インストール不要
 +
 
 +
===unity2020.2.0f1以前では===
 +
https://github.com/jilleJr/Newtonsoft.Json-for-Unity#readme
 +
からunitypackageをDLしインストール
 +
 
 +
==インストール確認==
 +
packageManagerにnewtonsoft.jsonが追加されてることを確認
 +
<pre>
 +
Packages/manifest.json
 +
+"jillejr.newtonsoft.json-for-unity" : "13.0.102"
 +
</pre>
  
==サンプル==
+
==サンプル(エンコード)==
 
<pre>
 
<pre>
 
using UnityEngine;
 
using UnityEngine;
行34: 行51:
 
ログ:name=aaa value=111
 
ログ:name=aaa value=111
  
==WebGLで出力したとき==
+
==サンプル(デコードのみ)==
以下エラーが出た
+
<pre>
 +
void OnClick()
 +
{
 +
  string json = "{\"Name\": \"aaaa\",\"Value\": 1111}";
 +
  Item item = JsonConvert.DeserializeObject<Item>(json);
 +
    Debug.Log("name=" + item.Name + " value=" + item.Value);
 +
    GameObject.Find("Text").GetComponent<Text>().text = "name=" + item.Name + " value=" + item.Value;
 +
}
 +
</pre>
 +
 
 +
==WebGLでobject.onAbortなエラーがでるとき==
 +
WebGLで出力したとき、
 +
JsonConvert.SerializeObjectや、JsonConvert.DeserializeObjectの部分で、以下object.onAbortなエラーが出る場合。
 
<pre>
 
<pre>
 
an error occurred runnning the unity content on this page.
 
an error occurred runnning the unity content on this page.
 
see your browser javascript console for more info.
 
see your browser javascript console for more info.
 +
the error was:
 +
uncaught abort(64) at error
 +
at jsStackTrack(Build.wasm.framework.unityweb:8:15602)
 +
at stackTrace [Object.stackTrace]
 +
(Build.wasm.framework.unityweb:8:15773)
 +
at object.onAbort(http://localhost:54514/Build/UnityLoader.js:4:11273)
 +
</pre>
 +
 +
以下dllでは、上記エラーが起き、うまくいかない。上の項目にあるように、unitypackageを使ってdllを設置すれば改善した。
 +
#https://www.nuget.org/packages/Newtonsoft.Json をDLし、.nupkgを.zipに変更し、解凍。
 +
#lib\netstandard2.0の下のNewtonsoft.Json.dllをAssets/Pluginsの下に設置するのではなく、
 +
 +
==Dictionaryでjsonを使う==
 +
===<int, string>の場合===
 +
<pre>
 +
void Decode() {
 +
        string json = "{1:'bbb',2:'aaa'}";
 +
        Dictionary<int, string> dic = JsonConvert.DeserializeObject<Dictionary<int, string>>(json);
 +
        Debug.Log(dic[1]); // bbb
 +
}
 +
</pre>
 +
 +
===<string, string>の場合===
 +
<pre>
 +
void Decode() {
 +
        string json = @"{
 +
                                'key1': 'taro',
 +
                                'key2': 'hoge'
 +
                            }";
 +
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
 +
        Debug.Log(dic["key1"]);
 +
}
 +
</pre>
 +
 +
===<string, User>の場合===
 +
User.cs
 +
<pre>
 +
public class User
 +
{
 +
    public string username;
 +
    public string email;
 +
    public User()
 +
    {
 +
    }
 +
    public User(string username, string email)
 +
    {
 +
        this.username = username;
 +
        this.email = email;
 +
    }
 +
}
 +
</pre>
 +
Main.cs
 +
<pre>
 +
void Decode() {
 +
        string json = "{'key1':{'username':'taro','email':'hoge@example'},'key2':{'username':'piyo','email':'piyo@example'}}";
 +
        Dictionary<string, User> dic = JsonConvert.DeserializeObject<Dictionary<string, User>>(json);
 +
        Debug.Log(dic["key2"].email); // piyo@example
 +
        foreach (KeyValuePair<string, User>  x in dic) {
 +
                    Debug.Log(x.Key + ": " + x.Value.email); // key1: hoge@example
 +
        }
 +
}
 +
void Encode() {
 +
        User user1 = new User("taro", "hoge@example");
 +
        User user2 = new User("piyo", "piyo@example");
 +
        Dictionary<string, User> dic = new Dictionary<string, User>()
 +
        {
 +
            { "key1", user1 },
 +
            { "key2", user2 },
 +
        };
 +
        string json = JsonConvert.SerializeObject(dic);
 +
        Debug.Log("json=" + json); // json={"key1":{"username":"taro","email":"hoge@example"},"key2":{"username":"piyo","email":"piyo@example"}}
 +
}
 +
</pre>
 +
==Listでjsonを使う==
 +
json例
 +
<pre>
 +
[{"Name":"aaa","Value":111},{"Name":"bbb","Value":222}]
 +
</pre>
 +
 +
エンコード
 +
<pre>
 +
List<Item> items = new List<Item>();
 +
Item itemSource = new Item();
 +
itemSource.Name = "aaa";
 +
itemSource.Value = 111;
 +
items.Add(itemSource);
 +
Item itemSource2 = new Item();
 +
itemSource2.Name = "bbb";
 +
itemSource2.Value = 222;
 +
items.Add(itemSource2);
 +
string json = JsonConvert.SerializeObject(items);
 +
Debug.Log("json=" + json);
 +
</pre>
 +
 +
デコード
 +
<pre>
 +
string json = "[{'Name':'aaa','Value':111},{'Name':'bbb','Value':222}]";
 +
List<Item> tmpItems = JsonConvert.DeserializeObject<List<Item>>(json);
 +
foreach (Item item in tmpItems)
 +
{
 +
    Debug.Log("name=" + item.Name + " value=" + item.Value);
 +
}
 
</pre>
 
</pre>
 +
参考:https://teratail.com/questions/212816
  
 
==参考==
 
==参考==

2023年7月24日 (月) 12:22時点における最新版

NewtonJsonをDL&インストール

unity2022以降

再度このライブラリは、入らなくなったっぽい。 unityメニュー/Windows/PackageManagerを開いて、左上の+、Add package from git URLから、以下を入れてインストールする

com.unity.nuget.newtonsoft-json

参考:https://qiita.com/T_keigo/items/ec6e864114697a846f70

unity2020.3.0f1以降では

最初から、Newtonsoft.Jsonが入ってる?ようで、インストール不要

unity2020.2.0f1以前では

https://github.com/jilleJr/Newtonsoft.Json-for-Unity#readme からunitypackageをDLしインストール

インストール確認

packageManagerにnewtonsoft.jsonが追加されてることを確認

Packages/manifest.json
+"jillejr.newtonsoft.json-for-unity" : "13.0.102"

サンプル(エンコード)

using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json;
using System;
public class SampleScene : MonoBehaviour
{
    [Serializable]
    public class Item
    {
        public string Name;
        public int Value;
    }
    void Start()
    {
        GameObject.Find("Button").GetComponent<Button>().onClick.AddListener(OnClick);
    }
    void OnClick()
    {
        Item itemSource = new Item();
        itemSource.Name = "aaa";
        itemSource.Value = 111;
        string json = JsonConvert.SerializeObject(itemSource);
        Item item = JsonConvert.DeserializeObject<Item>(json);
        Debug.Log("name=" + item.Name + " value=" + item.Value);
        GameObject.Find("Text").GetComponent<Text>().text = "name=" + item.Name + " value=" + item.Value;
    }

ログ:name=aaa value=111

サンプル(デコードのみ)

void OnClick()
{
   string json = "{\"Name\": \"aaaa\",\"Value\": 1111}";
   Item item = JsonConvert.DeserializeObject<Item>(json);
    Debug.Log("name=" + item.Name + " value=" + item.Value);
    GameObject.Find("Text").GetComponent<Text>().text = "name=" + item.Name + " value=" + item.Value;
}

WebGLでobject.onAbortなエラーがでるとき

WebGLで出力したとき、 JsonConvert.SerializeObjectや、JsonConvert.DeserializeObjectの部分で、以下object.onAbortなエラーが出る場合。

an error occurred runnning the unity content on this page.
see your browser javascript console for more info.
the error was:
uncaught abort(64) at error
at jsStackTrack(Build.wasm.framework.unityweb:8:15602)
at stackTrace [Object.stackTrace]
(Build.wasm.framework.unityweb:8:15773)
at object.onAbort(http://localhost:54514/Build/UnityLoader.js:4:11273)

以下dllでは、上記エラーが起き、うまくいかない。上の項目にあるように、unitypackageを使ってdllを設置すれば改善した。

  1. https://www.nuget.org/packages/Newtonsoft.Json をDLし、.nupkgを.zipに変更し、解凍。
  2. lib\netstandard2.0の下のNewtonsoft.Json.dllをAssets/Pluginsの下に設置するのではなく、

Dictionaryでjsonを使う

<int, string>の場合

void Decode() {
        string json = "{1:'bbb',2:'aaa'}";
        Dictionary<int, string> dic = JsonConvert.DeserializeObject<Dictionary<int, string>>(json);
        Debug.Log(dic[1]); // bbb
}

<string, string>の場合

void Decode() {
        string json = @"{
                                 'key1': 'taro',
                                 'key2': 'hoge'
                             }";
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
        Debug.Log(dic["key1"]);
}

<string, User>の場合

User.cs

public class User
{
    public string username;
    public string email;
    public User()
    {
    }
    public User(string username, string email)
    {
        this.username = username;
        this.email = email;
    }
}

Main.cs

void Decode() {
        string json = "{'key1':{'username':'taro','email':'hoge@example'},'key2':{'username':'piyo','email':'piyo@example'}}";
        Dictionary<string, User> dic = JsonConvert.DeserializeObject<Dictionary<string, User>>(json);
        Debug.Log(dic["key2"].email); // piyo@example
        foreach (KeyValuePair<string, User>  x in dic) {
                    Debug.Log(x.Key + ": " + x.Value.email); // key1: hoge@example
        }
}
void Encode() {
        User user1 = new User("taro", "hoge@example");
        User user2 = new User("piyo", "piyo@example");
        Dictionary<string, User> dic = new Dictionary<string, User>()
        {
            { "key1", user1 },
            { "key2", user2 },
        };
        string json = JsonConvert.SerializeObject(dic);
        Debug.Log("json=" + json); // json={"key1":{"username":"taro","email":"hoge@example"},"key2":{"username":"piyo","email":"piyo@example"}}
}

Listでjsonを使う

json例

[{"Name":"aaa","Value":111},{"Name":"bbb","Value":222}]

エンコード

List<Item> items = new List<Item>();
Item itemSource = new Item();
itemSource.Name = "aaa";
itemSource.Value = 111;
items.Add(itemSource);
Item itemSource2 = new Item();
itemSource2.Name = "bbb";
itemSource2.Value = 222;
items.Add(itemSource2);
string json = JsonConvert.SerializeObject(items);
Debug.Log("json=" + json);

デコード

string json = "[{'Name':'aaa','Value':111},{'Name':'bbb','Value':222}]";
List<Item> tmpItems = JsonConvert.DeserializeObject<List<Item>>(json);
foreach (Item item in tmpItems)
{
    Debug.Log("name=" + item.Name + " value=" + item.Value);
}

参考:https://teratail.com/questions/212816

参考

https://qiita.com/safu9/items/b9f654a5083d794442a2

https://spi8823.hatenablog.com/entry/2016/04/16/001641