facebook twitter hatena line email

Unity/Csharp/Json/NewtonJson

提供: 初心者エンジニアの簡易メモ
2021年9月29日 (水) 13:41時点におけるAdmin (トーク | 投稿記録)による版 (の場合)

移動: 案内検索

NewtonJsonをDL&インストール

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

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

インストール確認

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
}

参考

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

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