【问题标题】:Can I use a JSON string in C#?我可以在 C# 中使用 JSON 字符串吗?
【发布时间】:2019-02-12 14:25:20
【问题描述】:

为我在 Windows Visual Studio 中构建的 android 重建一个 java 应用程序。需要有关在 Visual Studio Visual C# Forms 应用程序 (.NET Framework) 中使用 JSON 字符串的帮助。

我正在创建一种新的文件格式,以便能够将数据传输到我公司的不同机器人。我为我的 android 应用程序使用了一个列表映射,该文件包含一个 JSON 字符串。是否可以将字符串添加到 Visual C# Forms (.NET Framework) 上的列表中以在列表框中查看?提供样品。

[{"VALUE":"03","ATTRIBUTE":"Laayelbxw"},
 {"VALUE":"01","ATTRIBUTE":"Leruaret"},
 {"VALUE":"08","ATTRIBUTE":"Lscwbryeiyabwaa"},
 {"VALUE":"09","ATTRIBUTE":"Leruxyklrwbwaa"}]

【问题讨论】:

  • 是的,你可以拥有。
  • Deserialize JSON with C#的可能重复
  • 添加一个重要说明:确保所有对象的属性都已实例化,因为如果其中任何一个未设置为引用,JsonConvert.DeserializeObject() 将失败。
  • @MahdiBenaoun 你说的 "all the object's attributes are instanciated" 是什么意思?你的意思是所有的json成员都设置好了?

标签: c# arrays json visual-studio-2017


【解决方案1】:

当然可以!

我知道在 C# 中反序列化 JSON 的最简单方法是使用 Newtonsoft Json nuget package

例如:

/*
 * This class represent a single item of your collection.
 * It has the same properties name than your JSON string members
 * You can use differents properties names, but you'll have to use attributes
 */
class MyClass
{
    public int VALUE { get; set; }
    public string ATTRIBUTE { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var myJSON = "[{\"VALUE\":\"03\",\"ATTRIBUTE\":\"Laayelbxw\"},{\"VALUE\":\"01\",\"ATTRIBUTE\":\"Leruaret\"},{\"VALUE\":\"08\",\"ATTRIBUTE\":\"Lscwbryeiyabwaa\"},{\"VALUE\":\"09\",\"ATTRIBUTE\":\"Leruxyklrwbwaa\"}]";

        //                 V---------V----- Namespace is Newtonsoft.Json
        var MyCollection = JsonConvert.DeserializeObject<List<MyClass>>(myJSON);
        // Tadaam ! You now have a collection of MyClass objects created from that json string

        foreach (var item in MyCollection)
        {
            Console.WriteLine("Value : " + item.VALUE);
            Console.WriteLine("Attribute : " + item.ATTRIBUTE);
        }
        Console.Read();
    }
}

输出

Value : 3
Attribute : Laayelbxw
Value : 1
Attribute : Leruaret
Value : 8
Attribute : Lscwbryeiyabwaa
Value : 9
Attribute : Leruxyklrwbwaa

【讨论】:

  • 感谢您提供比我最好的答案,它解释得很好^^
  • 我很想知道为什么我被否决了。有人知道吗?
  • 我也很感兴趣,希望@downvoter解释一下,如果有什么问题,可能是因为重复,你是这么认为的吗?
【解决方案2】:

会是这样的。

public class JsonExample
{
    public int VALUE { get; set; }

    public string ATTRIBUTE { get; set; }
}

public void GetJson()
{
    string json = "your string";
    var xpto = JsonConvert.DeserializeObject<List<JsonExample>>(json);
}

【讨论】:

  • 你的回答也不错,当你想发帖的时候,@Cid 比你发他自己的快。
  • 是的,我的速度有点快,但你仍然值得一票,因为你的答案是准确的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 2010-10-06
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 2020-06-11
相关资源
最近更新 更多