简体   繁体   English

如何使用Newtonsoft.Json反序列化JsonArray?

[英]How to deserialize a JsonArray using Newtonsoft.Json?

Hi I have the following code and from it I want to get some fields and put into an Android.TextView 嗨,我有以下代码,并从中获取一些字段并放入Android.TextView中

using System;
using Android.App;
using Android.Widget;
using Android.OS;
using RestSharp;
using Newtonsoft.Json;
using Android.Util;
using App4.Resources;
using Newtonsoft.Json.Linq;
using Org.Json;
using System.Net;
using System.IO;
using System.Collections.Generic;

namespace App4
{
[Activity(Label = "App4", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    EditText edtcpf;
    Button btnConsumer;
    TextView txtcpf;
    RestRequest cpf { get; set; }
    public RestClient consumer { get; set; }
    IRestResponse mensagemConsumer;
    TextView txtsobrenome;
    RestClient orderId { get; set; }
    RestRequest requestorderId { get; set; }
    IRestResponse answerorder { get; set; }
    TextView txtnome;
    TextView txtorder;
    TextView txtmensagem;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        btnConsumer = FindViewById<Button>(Resource.Id.btnConsumer);
        edtcpf = FindViewById<EditText>(Resource.Id.edtcpf);
        txtcpf = FindViewById<TextView>(Resource.Id.txtcpf);
        txtsobrenome = FindViewById<TextView>(Resource.Id.txtresposta);
        txtnome = FindViewById<TextView>(Resource.Id.txtNome);
        txtorder = FindViewById<TextView>(Resource.Id.txtorder);
        txtmensagem = FindViewById<TextView>(Resource.Id.txtMensagem);
        btnConsumer.Click += BtnConsumer_Click;

    }

    private void BtnConsumer_Click(object sender, EventArgs e)
    {
        try
        {
            // API Consumer CPF

            consumer = new RestClient("https://qa.api-latam.whirlpool.com/v1.0/consumers");
            cpf = new RestRequest("/" + edtcpf.Text, Method.GET);
            cpf.AddHeader("Content-Type", "application/json; charset=utf-8");
            cpf.AddHeader("Authorization", "Bearer 70197e6c-d81b-384c-bb32-d69e8c10b101");
            mensagemConsumer = consumer.Execute(cpf);
            Pessoa pessoa = JsonConvert.DeserializeObject<Pessoa>(mensagemConsumer.Content);
            txtnome.Text = "Nome: " +pessoa.firstName;
            txtsobrenome.Text = "Sobrenome: "+ pessoa.lastName;

            // API Consumer Appliances
            orderId = new RestClient("https://qa.api-latam.whirlpool.com/v1.0/consumers/");
            requestorderId = new RestRequest("/"+ edtcpf.Text+ "/service-orders", Method.GET);
            requestorderId.AddHeader("Content-Type", "application/json; charset=utf-8");
            requestorderId.AddHeader("Authorization", "Bearer 70197e6c-d81b-384c-bb32-d69e8c10b101");
            answerorder = orderId.Execute(requestorderId);
            CustomerJson json = JsonConvert.DeserializeObject<List<CustomerJson>>(json);
            txtorder.Text = json.Customer.orderId;





        }
        catch (Exception)
        {

            throw;
        }




    }


}

} }

And I'm trying to Deserialize a JsonResponse that is an array, here is the response I get from the API: 我正在尝试反序列化一个数组的JsonResponse,这是我从API获得的响应:

**{
  "orders": [
   {
  "order": {
    "orderId": 7004093603,
    "orderStatusCode": "CANC",
    "orderStatusDescription": "Cancelado",
    "serviceProviderId": 3649,
    "orderOpeningDate": "2015-07-07",
    "orderSchedulingDate": "2015-07-18",
    "orderSchedulingPeriod": "M",
    "orderSettlementDate": null,
    "orderCancellationDate": null
  }
},
{
  "order": {
    "orderId": 7004153791,
    "orderStatusCode": "AGEN",
    "orderStatusDescription": "Agendado",
    "serviceProviderId": 3524,
    "orderOpeningDate": "2016-08-31",
    "orderSchedulingDate": "2016-09-01",
    "orderSchedulingPeriod": "M",
    "orderSettlementDate": null,
    "orderCancellationDate": null
  }
},
{
  "order": {
    "orderId": 7004156972,
    "orderStatusCode": "ABRT",
    "orderStatusDescription": "Aberto",
    "serviceProviderId": 30820,
    "orderOpeningDate": "2017-04-13",
    "orderSchedulingDate": null,
    "orderSchedulingPeriod": null,
    "orderSettlementDate": null,
    "orderCancellationDate": null
  }
},
{
  "order": {
    "orderId": 7002178478,
    "orderStatusCode": "CANC",
    "orderStatusDescription": "Cancelado",
    "serviceProviderId": 3555,
    "orderOpeningDate": "2014-02-22",
    "orderSchedulingDate": "2014-02-24",
    "orderSchedulingPeriod": "M",
    "orderSettlementDate": null,
    "orderCancellationDate": null
  }
},
{
  "order": {
    "orderId": 7002118317,
    "orderStatusCode": "CANC",
    "orderStatusDescription": "Cancelado",
    "serviceProviderId": 3555,
    "orderOpeningDate": "2014-02-10",
    "orderSchedulingDate": "2014-02-15",
    "orderSchedulingPeriod": "M",
    "orderSettlementDate": null,
    "orderCancellationDate": null
    }
    }
    ]
    }**

I created a class that has this strings 我创建了一个具有此字符串的类

 class RootObject
{
 [JsonProperty("orders")]
public Results Results { get; set; }
}

class Results
{
[JsonProperty("order")]
public Dictionary<string, JobCode> JobCodes { get; set; }
}

class JobCode
{
[JsonProperty("orderId")]
public string orderId { get; set; }
[JsonProperty("orderStatusCode")]
public string orderStatusCode { get; set; }
[JsonProperty("orderStatusDescription")]
public string orderStatusDescription { get; set; }
  }

The fields that I need to insert into the applicative are orderId orderStatusCode and orderStatusDescription. 我需要插入到应用程序中的字段是orderId orderStatusCode和orderStatusDescription。

I'm trying to deserialize it but it returns this message: Argument 1: cannot convert from 'CustomerJson' to 'string' and Use of Unassigned local variable 'json' 我正在尝试反序列化,但它返回此消息: 参数1:无法从'CustomerJson'转换为'string'并使用未分配的局部变量'json'

How can I deserialize this? 我该如何反序列化?

IMPORTANT THING 重要的事情

1) Order is sub-element of orders[] array. 1)订单是orders []数组的子元素。

2) Customer is sub-element of Order. 2)客户是订单的子元素。

You should search in oders[] array step by step with an enumarator, a loop, and so on... And then, When every every loop is complete, you should parse Customer class in order element. 您应该使用枚举器,循环等等一步一步地搜索oders []数组...然后,当每个循环都完成后,应该在order元素中解析Customer类。

Example; 例;

foreach(var order in orders)
{ 
   var order = order.name;
   //access to order data;
}

Deserialize JSON to C# Classes 将JSON反序列化为C#类

Your json is incorrect, you're missing a '}'. 您的json不正确,您丢失了'}'。 Here's the valid json 这是有效的json

{
  "orders": [{
    "order": {
        "orderId": 7004093603,
        "orderStatusCode": "CANC",
        "orderStatusDescription": "Cancelado",
        "serviceProviderId": 3649,
        "orderOpeningDate": "2015-07-07",
        "orderSchedulingDate": "2015-07-18",
        "orderSchedulingPeriod": "M",
        "orderSettlementDate": null,
        "orderCancellationDate": null
    }
  }]
}

Also, I created the model using http://json2csharp.com/ I'm pasting them below. 另外,我使用http://json2csharp.com/创建了模型,并将其粘贴在下面。 Try parsing your json with the following model, it should work 尝试使用以下模型解析json,它应该可以正常工作

public class Order2 {
  public long orderId { get; set; }
  public string orderStatusCode { get; set; }
  public string orderStatusDescription { get; set; }
  public int serviceProviderId { get; set; }
  public string orderOpeningDate { get; set; }
  public string orderSchedulingDate { get; set; }
  public string orderSchedulingPeriod { get; set; }
  public object orderSettlementDate { get; set; }
  public object orderCancellationDate { get; set; }
}

public class Order{
  public Order2 order { get; set; }
}

public class RootObject{
  public List<Order> orders { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM