首页 > 解决方案 > 当前代码的 C# 读/写 Json 问题

问题描述

错误:错误 CS0103:当前上下文中不存在名称“JsonConvert”

我有最新的 Newtonsoft 下载,但我想不出任何方法来解决这个问题。我已经浏览了大约 50 个不同的链接,都说要安装它。它是什么。

我错过了一些小东西吗?我只是想将我的 json 元素添加到列表中,以便可以在程序中使用它们,然后写回 Json 文件。如果这不起作用,有人可以链接或向我展示另一种在 c# 中执行此操作的方法吗?

using System.IO;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;

namespace Newtonsoft.Json {
public class CustomControls : MonoBehaviour
{
    private List<string> controls;

    //public object JsonConvert { get; private set; }

    // Start is called before the first frame update
    void Start()
    {
        LoadJson();
        for (int i = 0; i < controls.Count; i++)
        {
            Debug.Log(controls[i].ToString());
        }
    }

    public void LoadJson()
    {
        using (StreamReader r = new StreamReader("CustomControls.json"))
        {
            string json = r.ReadToEnd();
            controls = JsonConvert.DeserializeObject<List<string>>(json);
        }
    }
}
}

标签: c#jsonlistunity3d

解决方案


在代码中更改命名空间的名称

using System.IO;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;

namespace AnythingOtherThanNewtonsoft.Json {
public class CustomControls : MonoBehaviour
{
    private List<string> controls;

    //public object JsonConvert { get; private set; }

    // Start is called before the first frame update
    void Start()
    {
        LoadJson();
        for (int i = 0; i < controls.Count; i++)
        {
            Debug.Log(controls[i].ToString());
        }
    }

    public void LoadJson()
    {
        using (StreamReader r = new StreamReader("CustomControls.json"))
        {
            string json = r.ReadToEnd();
            controls = JsonConvert.DeserializeObject<List<string>>(json);
        }
    }
}
}

推荐阅读