Привет, у меня есть следующий код, согласно которому в моем классе я определил все классы, которые мне понадобятся для построения моей строки 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; }
}
}