首页 > 解决方案 > 将两个单独的数据字段存储到一个数组中 c# Array Json from Class

问题描述

嗨,我有以下代码,在我的课堂上,我已经定义了JSON为最终的 put 请求构建字符串所需的所有类。我正在尝试将我的AttributeColorAttributeSize字段放入该属性string[]中,以便JSON返回以下内容:

{"group":null,"productid":"42","sku":"211","money":"20.00","categoryid":"42","attributes":["42","green"]}
myObject.attributes = reader["Sizeattribute"].ToString() + reader["ColorAttribute"].ToString();

我哪里错了?如何将两个字段添加到这个数组以获得完美的 JSON?现在我收到错误无法将类型隐式转换'string''string[]'

代码片段:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace JSON_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Read From SQL 
            using (SqlConnection connection = new SqlConnection("Server = localhost;Database=xxxx;UID=admin;PASSWORD=xxxx"))
            {
                String query = "SELECT * FROM [test].[dbo].[DimProductVariantXXX] "; // Please Change the View that you are pointing towards

                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    connection.Open();
                    List<Product> myObjectList = new List<Product>();
                    var reader = command.ExecuteReader();
                    if (reader.HasRows)

                    {
                        while (reader.Read())
                        {
                            Product myObject = new Product();
                            myObject.productid = reader["productid"].ToString();
                            myObject.sku = reader["sku"].ToString();
                            myObject.money = reader["money"].ToString();
                            //  myObject.categoryid = Convert.ToString(reader["categoryid"]);
                            myObject.attributes = reader["Sizeattribute"].ToString() + reader["ColorAttribute"].ToString();
                            //    myObject.variantparentid = reader["variantparentid"].ToString();
                            myObjectList.Add(myObject);
                        }
                    }
                    Console.WriteLine(myObjectList);
                    Product product = new Product();
                    String JSONresult = JsonConvert.SerializeObject(product);
                    string path = @"D:\json\product.json";
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                        using (var tw = new StreamWriter(path, true))
                        {
                            tw.WriteLine(JSONresult.ToString());
                            tw.Close();
                        }
                    }
                    else if (!File.Exists(path))
                    {
                        using (var tw = new StreamWriter(path, true))
                        {
                            tw.WriteLine(JSONresult.ToString());
                            tw.Close();
                        }
                    }
                }
            }
        }
    }
    class Product
    {
        public Group group;
        public string productid { get; set; }
        public string sku { get; set; }
        public string money { get; set; }
        public string categoryid { get; set; }
        public string sizeattribute { get; set; }
        public string colorattribute { get; set; }
        public List<string>[] attributes { get; set; }

    }
}

标签: c#arrays.netjsonclass

解决方案


Product类中,attributes属性应定义为单个列表或数组。它目前被定义为一个数组List<string>(不确定这是否是一个错字)。

更新定义:

public List<string> attributes { get; set; }

现在,myObject.attributes是一个List<string>,所以您需要初始化列表并将值添加到其中。

您可以使用Collection Initializer执行此操作:

myObject.attributes = new List<string> 
                      { 
                          reader["Sizeattribute"].ToString(), 
                          reader["ColorAttribute"].ToString() 
                      };

这应该会产生预期的 JSON。


推荐阅读