You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware客户API提交含列表的对象数据问题求助

解决Shopware客户API提交时列表未序列化的问题

我来帮你排查下问题所在,你遇到的情况主要是两个核心问题导致的:

  • 你的billing字段是private的,默认JSON序列化器(不管是Newtonsoft.Json还是System.Text.Json)都不会序列化私有成员,所以这部分数据根本不会被转成JSON。
  • 另外,Shopware API要求的billing是单个对象,但你定义的是List<Customer>类型,就算能序列化也会变成数组,完全不符合API的格式要求。

接下来咱们一步步修正:

1. 重构Customer类的结构

首先调整billing的类型和访问权限,同时推荐把字段改成C#规范的属性(序列化器对公共属性的支持更友好,也符合编码最佳实践):

public class Customer
{
    // 改为公共属性,符合C#编码规范
    public string Email { get; set; }
    public string Salutation { get; set; }
    public string Title { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string Zipcode { get; set; }
    public int Country { get; set; }

    // 改成单个Customer对象,匹配Shopware API的格式,设为公共属性
    public Customer Billing { get; set; }

    // 保留无参构造函数,序列化器可能需要用到
    public Customer() { }
}

2. 调整控制器的实例化逻辑

现在不需要创建List了,直接实例化单个Customer作为Billing对象即可:

// 直接创建单个billing对象,而非List
var billing = new Customer() 
{ 
    Firstname = "Hassas", 
    Lastname = "sssss", 
    Salutation = "mr", 
    Street = "Haupt Str 11", 
    City = "abcddd", 
    Zipcode = "4900", 
    Country = 2 
};

var shopCustomer = new Customer();
shopCustomer.Firstname = customers.FirstName;
shopCustomer.Lastname = customers.LastName;
shopCustomer.Email = customers.Email;
shopCustomer.Salutation = "mr";
// 将单个billing对象赋值给Billing属性
shopCustomer.Billing = billing;

// 现在提交这个对象,序列化后就会包含完整的billing数据了
customershopwareApi.getCustomerRessource().add(shopCustomer);

3. 适配API的大小写格式(可选)

如果你的API期望小驼峰命名(比如示例里的email而非Email),可以通过序列化配置或者特性来调整:

  • 用Newtonsoft.Json的话,可设置序列化器的命名策略:
    var settings = new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    string json = JsonConvert.SerializeObject(shopCustomer, settings);
    
  • 用System.Text.Json的话,配置命名策略:
    var options = new JsonSerializerOptions
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };
    string json = JsonSerializer.Serialize(shopCustomer, options);
    

调整后序列化出的JSON就完全匹配你期望的Shopware API格式了。

内容的提问来源于stack exchange,提问作者Hassan Shabbir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:12:37