且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将JSON反序列化为对象(VB.NET)

更新时间:2023-01-17 07:37:50

我建议使用JSON.net,就像SBlackler一样。我根据您的对象和您发布的JSON对象在C#中编写了一个测试,并且能够很好地构建所有内容。这是我的代码。

I'd recommend JSON.net, as SBlackler did. I wrote up a test in C# based on your objects and the JSON object you posted and was able to build everything fine. Here's my code.

        List<items> Results = new List<items>();
        foreach (JToken Item in (JArray)JObject.Parse(json)["items"])
        {
            Results.Add(new items()
            {
                kind = Item["kind"].ToString(),
                product = new product()
                {
                    inventories = new inventories()
                    {
                        price = Convert.ToDouble(Item["product"]["inventories"][0]["price"].ToString())
                    }
                }
            });
        }
        Response.Write(Results[0].product.inventories.price);

我不太确定json对象的结构,但是清单似乎是一个数组。在您发布的示例中,您似乎试图获取该数组中第一个对象的价格值,而我的代码做到了。如果库存数组中有多个对象,则可能需要调整对象以及相应地填充它们的代码。

I'm a bit unsure of the structure of the json object, but inventories appears to be an array. Within the example you posted, it appeared that you were trying to get the "price" value of the first object inside that array, and my code does that. If there are multiple objects in the inventories array, you may want to adjust your objects and the code that populates them accordingly.

这是我的对象:

class items
{
    public product product { get; set; }
    public string kind { get; set; }
}

class product
{
    public inventories inventories { get; set; }
}

class inventories
{
    public double price { get; set; }
}

上面的代码假设库存中始终至少有一个对象数组,并且只会从第一个数组拉出。以下是在库存数组中有多个对象的情况下如何重构代码的方法。

The above code assumes there will ALWAYS be at least one object in the inventories array and will only pull from the first one. Following is how you might want to reconstruct the code should there be multiple objects in the inventories array.

    List<item> Results = new List<item>();
    foreach (JToken Item in (JArray)JObject.Parse(json)["items"])
    {
        item CurrentItem = new item()
        {
            kind = Item["kind"].ToString(),
            product = new product()
        };
        foreach (JToken inventory in (JArray)Item["product"]["inventories"])
        {
            CurrentItem.product.inventories.Add(new inventory()
            {
                price = Convert.ToDouble(inventory["price"].ToString())
            });
        }
        Results.Add(CurrentItem);
    }
    Response.Write(Results[0].product.inventories[0].price);

修改后的对象

class item
{
    public product product { get; set; }
    public string kind { get; set; }
}

class product
{
    public List<inventory> inventories { get; set; }

    public product()
    {
        inventories = new List<inventory>();
    }
}

class inventory
{
    public double price { get; set; }
}

我希望这可以解决您所寻找的问题。祝你好运!

I hope this solves what you were looking for. Good luck!