facebook twitter hatena line email

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

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(サンプル)
(サンプルjson化)
行12: 行12:
 
</pre>
 
</pre>
  
==サンプルjson化==
+
==サンプルエンコード==
 
<pre>
 
<pre>
 
using UnityEngine;
 
using UnityEngine;

2021年9月29日 (水) 13:11時点における版

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の下に設置するのではなく、

参考

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

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