【问题标题】:Shopify Sharp C#.NET library with JSON deserializingShopify Sharp C#.NET 库与 JSON 反序列化
【发布时间】:2019-12-18 22:23:32
【问题描述】:

这几天我一直在纠结这个问题,所以我想我最好问问论坛。

我正在使用 ShopifySharp C# 库进行 API 调用,但在反序列化产品时遇到问题。

我的应用需要获取特定时间段的订单价值,然后遍历每个订单的订单项以检索产品。本质上,我的流程是在 Bronto 中动态构建产品评论提醒电子邮件。

无论如何,不​​工作的部分如下:

这是我的调用方法:

public List<T> CallService<T>(string query)
    {

        var data = new List<T>();
        var fullyEscapedUri = _ShopUri.AbsoluteUri.EndsWith("/") ? _ShopUri : new Uri(_ShopUri + "/");
        var uri = new Uri(fullyEscapedUri, typeof(T).Name);

        if (!string.IsNullOrWhiteSpace(query))
        {

            var uriBuilder = new UriBuilder(uri) { Query = query };
            uri = uriBuilder.Uri;

        }

        string url = String.Format("{0}{1}", _ShopUri, query);

        // The WebRequest method will compile for .net4.5 but not 1.4.
        var request = WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "application/json";

        string base64EncodedUsernameAndPassword = string.Format("{0}:{1}", _Username, _Password);
        string authHeader = string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(base64EncodedUsernameAndPassword)));
        request.Headers["Authorization"] = authHeader;

        using (var response = request.GetResponse())
        {

            using (var stream = response.GetResponseStream())
            {

                using (var reader = new StreamReader(stream))
                {

                    string json = reader.ReadToEnd();                                  
                    var jsonObj = JsonConvert.DeserializeObject(json) as JObject;
                    var jsonArray = jsonObj[_ObjectType] as JArray; // code is crashing here for product json. Order json is being parsed fine.

                    foreach (var jsonEmp in jsonArray)
                    {

                        var obj = JsonConvert.DeserializeObject<T>(jsonEmp.ToString());
                        data.Add(obj);
                    }

                }

            }

        }

        return data;
    }

当它碰到产品时,它会在这一行崩溃,留下一个空的 jsonArray JArray:

var jsonArray = jsonObj[_ObjectType] as JArray; // code is crashing here for product json. Order json is being parsed fine.

我已经验证了进入这个函数的所有变量都很好(查询 URL、ObjectType、用户名、密码......)。我已经验证了问题行之前的代码是否返回了预期的 JSON 字符串。

这是返回的 JSON - 我只获取两个字段:

{
  "product": {
    "handle": "my-product-handle",
    "images": [
      {
        "id": 11112222333444,
        "product_id": 1234567890,
        "position": 1,
        "created_at": "2018-12-11T16:05:26-06:00",
        "updated_at": "2018-12-11T16:05:26-06:00",
        "alt": null,
        "width": 800,
        "height": 800,
        "src": "https://cdn.shopify.com/some_url",
        "variant_ids": [],
        "admin_graphql_api_id": "gid://shopify/ProductImage/some_other_url"
      }
    ]
  }
}

这是我相关的 C# 类:

public class Product : ShopifyObject
{
    /// <summary>
    /// The name of the product. In a shop's catalog, clicking on a product's title takes you to that product's page.
    /// On a product's page, the product's title typically appears in a large font.
    /// </summary>
    [JsonProperty("title")]
    public string Title { get; set; }

    /// <summary>
    /// The description of the product, complete with HTML formatting.
    /// </summary>
    [JsonProperty("body_html")]
    public string BodyHtml { get; set; }

    /// <summary>
    /// The name of the vendor of the product.
    /// </summary>
    [JsonProperty("vendor")]
    public string Vendor { get; set; }

    /// <summary>
    /// A categorization that a product can be tagged with, commonly used for filtering and searching.
    /// </summary>
    [JsonProperty("product_type")]
    public string ProductType { get; set; }

    /// <summary>
    /// The date and time when the product was created. The API returns this value in ISO 8601 format.
    /// </summary>
    [JsonProperty("created_at", DefaultValueHandling = DefaultValueHandling.Ignore)]
    public DateTimeOffset? CreatedAt { get; set; }

    /// <summary>
    /// A human-friendly unique string for the Product automatically generated from its title.
    /// They are used by the Liquid templating language to refer to objects.
    /// </summary>
    [JsonProperty("handle")]
    public string Handle { get; set; }

    /// <summary>
    /// The date and time when the product was last modified. The API returns this value in ISO 8601 format.
    /// </summary>
    [JsonProperty("updated_at", DefaultValueHandling = DefaultValueHandling.Ignore)]
    public DateTimeOffset? UpdatedAt { get; set; }

    /// <summary>
    /// The date and time when the product was published. The API returns this value in ISO 8601 format. 
    /// Set to NULL to unpublish a product
    /// </summary>
    [JsonProperty("published_at", DefaultValueHandling = DefaultValueHandling.Include, NullValueHandling = NullValueHandling.Include)]
    public DateTimeOffset? PublishedAt { get; set; }

    /// <summary>
    /// The suffix of the liquid template being used.
    /// By default, the original template is called product.liquid, without any suffix.
    /// Any additional templates will be: product.suffix.liquid.
    /// </summary>
    [JsonProperty("template_suffix")]
    public object TemplateSuffix { get; set; }

    /// <summary>
    /// A categorization that a product can be tagged with, commonly used for filtering and searching.
    /// Each comma-separated tag has a character limit of 255.
    /// </summary>
    [JsonProperty("tags")]
    public string Tags { get; set; }

    /// <summary>
    /// The sales channels in which the product is visible.
    /// </summary>
    [JsonProperty("published_scope")]
    public string PublishedScope { get; set; }

    /// <summary>
    /// A list of variant objects, each one representing a slightly different version of the product.
    /// For example, if a product comes in different sizes and colors, each size and color permutation (such as "small black", "medium black", "large blue"), would be a variant.
    /// To reorder variants, update the product with the variants in the desired order.The position attribute on the variant will be ignored.
    /// </summary>
    [JsonProperty("variants")]
    public IEnumerable<ProductVariant> Variants { get; set; }

    /// <summary>
    /// Custom product property names like "Size", "Color", and "Material".
    /// Products are based on permutations of these options. 
    /// A product may have a maximum of 3 options. 255 characters limit each.
    /// </summary>
    [JsonProperty("options")]
    public IEnumerable<ProductOption> Options { get; set; }

    /// <summary>
    /// A list of image objects, each one representing an image associated with the product.
    /// </summary>
    [JsonProperty("images")]
    public IEnumerable<ProductImage> Images { get; set; }
}

和产品图片:

public class ProductImage : ShopifyObject
{
    /// <summary>
    /// The id of the product associated with the image.
    /// </summary>
    [JsonProperty("product_id")]
    public long? ProductId { get; set; }

    /// <summary>
    /// The order of the product image in the list. The first product image is at position 1 and is the "main" image for the product.
    /// </summary>
    [JsonProperty("position")]
    public int? Position { get; set; }

    /// <summary>
    /// The date and time when the product image was created. The API returns this value in ISO 8601 format.
    /// </summary>
    [JsonProperty("created_at")]
    public DateTimeOffset? CreatedAt { get; set; }

    /// <summary>
    /// The date and time when the product image was last modified. The API returns this value in ISO 8601 format.
    /// </summary>
    [JsonProperty("updated_at")]
    public DateTimeOffset? UpdatedAt { get; set; }

    /// <summary>
    /// Specifies the alt tag of the product image.
    /// </summary>
    [JsonProperty("alt")]
    public object Alt { get; set; }

    /// <summary>
    /// Specifies the width of the product image.
    /// </summary>
    [JsonProperty("width")]
    public int? width { get; set; }

    /// <summary>
    /// Specifies the height of the product image.
    /// </summary>
    [JsonProperty("height")]
    public int? height { get; set; }

    /// <summary>
    /// Specifies the location of the product image.
    /// </summary>
    [JsonProperty("src")]
    public string Src { get; set; }

    /// <summary>
    /// An array of variant ids associated with the image.
    /// </summary>
    [JsonProperty("variant_ids")]
    public IEnumerable<long> VariantIds { get; set; }

    /// <summary>
    /// An array of variant ids associated with the image.
    /// </summary>
    [JsonProperty("admin_graphql_api_id")]
    public string AdminGraphQlApiId { get; set; }
}

有什么想法吗?

【问题讨论】:

    标签: c# json json.net shopify


    【解决方案1】:

    IMO 你不需要为一些项目上课。我会给你一个我的代码 sn-p 的例子。

     Stream dataStream = response.GetResponseStream();
     StreamReader reader = new StreamReader(dataStream);
     string responseFromServer = reader.ReadToEnd();
     var data = (JObject)JsonConvert.DeserializeObject(responseFromServer);
     var products = data["products"].Children();
    
     foreach (var product in products)
            { 
             Console.WriteLine("the prod ID number : "+product["id"]);
    
            }
    

    您可以使用数组索引从 json 获取任何产品项目信息。 希望这能推动你朝着正确的方向前进。或者至少给你一些思考。

    【讨论】:

    • 除了在我的情况下,我返回的是“产品”对象,而不是“产品”。我认为我的问题不在于我试图将单个元素放入 JArray....或者这可能是问题所在?
    【解决方案2】:

    我最终只使用 products.json 端点,而不是通过 ID (product/{product ID}.json) 检索单个端点。然后我从整个序列化的产品列表中获取订单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 2020-06-30
      相关资源
      最近更新 更多