[英]Storing two seperate data fields into an array c# Array Json from Class
嗨,我有以下代码,在我的 class 中,我已经定义了为最终的 put 请求构建JSON
字符串所需的所有类。 我正在尝试将我的AttributeColor
和AttributeSize
字段放入该属性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; }
}
}
在Product
class 中, 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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.