如何使用.Text序列化和反序列化Json var

问题描述:

您好我正在使用Xamarin来处理android。我编写了一个代码来从WSO2调用API,它返回的答案取决于用户发送的ID。它返回的内容这样的JSON:如何使用.Text序列化和反序列化Json var

{ “consumerId”:56704292158, “的categoryId”:1, “categoryDe​​scription”: “佩索阿”, “名字”: “FN”,” lastName“,”fiscalDocuments“:[{”fiscalDocument“:{”documentType“:”Brasil:nºCPF“,”cpf“:199999992}}],”gender“:”M“,”emailAddress“ : “:R **** @ * COM”, “optIns”:[{ “选择启用”:{ “名优产品”: “领事”, “acceptanceStatus”:假}},{ “选择启用”:{ “名优产品”: “brastemp”, “acceptanceStatus”:真}}], “communicationData”:[{ “communicationInfo”:{ “addressId”:2 **** 03, “PHONENUMBERS”:[{ “phoneNumber的”:{ “PHONETYPE”: “mobilePhone”,“phoneNumber”:5555555555}}],“streetAddress”:“ANY STREET”,“streetNumber”:123,“streetComplement”:null,“streetDistrict”:“AN Y城市“,”cityName“:”ANY CITY“,”stateCode“:”XX“,”zipCode“:”12345“,”locationReferences“:[{”locationReference“:”Mercado“}],”countryCode“ ZZ “}},{” communicationInfo “:{” addressId “:2.563244E + 7”,PHONENUMBERS “:[{” phoneNumber的 “:{” PHONETYPE “:” mobilePhone “ ”phoneNumber的“:5555555555}},{” phoneNumber的“:{”phoneType“:”homePhone“,”phoneNumber“:555555555}}],”streetAddress“:”ANY STREET“,”streetNumber“:123,”streetComplement“:”CASA“,”streetDistrict“ “,”cityName“:”ANY CITY“,”stateCode“:”XX“,”zipCode“:”12345“,”locationReferences“:[{”locationReference“:”Ao lado do deposito lua nova“}] “:”ZZ“}}]}

我只想从这个字段获取firstName和lastName。我试图序列化这个,但我认为我做错了什么。下面是代码

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; 

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 txtresposta; 
     RestClient orderId { get; set; } 
     RestRequest requestorderId { get; set; } 
     IRestResponse answer { get; set; } 
     IRestResponse answerorder { get; set; } 
     TextView txtnome; 
     public string raika; 
     private string teamname; 
     private JToken primeironome; 

     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); 
      txtresposta = FindViewById<TextView>(Resource.Id.txtresposta); 
      txtnome = FindViewById<TextView>(Resource.Id.txtNome); 
      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); 
       string nombre = Convert.ToString(mensagemConsumer.Content); 
       Nome nome = new Nome(); 
       string json = JsonConvert.SerializeObject(mensagemConsumer.Content, Formatting.Indented); 
       nome.firstName = mensagemConsumer.Content; 

       Log.Info("info ",json); 
       txtresposta.Text = json; 

       //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); 
       txtnome.Text = answerorder.Content; 
       string respostaorder = Convert.ToString(answerorder); 
       dynamic deserializado = JsonConvert.DeserializeObject(respostaorder); 
      } 
      catch (Exception) 
      { 
       throw; 
      } 
     } 
    } 
} 

这里是获取类,并设置

using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

using Android.App; 
using Android.Content; 
using Android.OS; 
using Android.Runtime; 
using Android.Views; 
using Android.Widget; 

namespace App4.Resources 
{ 
    public class Nome 
    { 
     public string firstName { get; set;} 
     public string lastName { get; set; } 
    } 
} 

我如何序列化和与使用取决于像。文本一edtcpf.Text一个变种反序列化JSON这及其内容?

我只想得到从这个字段firstName和lastName。

对于这个要求,你可以在你的项目中安装Newtonsoft.Json package再例如:

TextView tvfirst = FindViewById<TextView>(Resource.Id.firstname); 
TextView tvlast = FindViewById<TextView>(Resource.Id.lastname); 

Button btn = FindViewById<Button>(Resource.Id.btn); 
btn.Click += (sender, e) => 
{ 
    var jsonstring = @"{'consumerId':56704292158, 'categoryId':1, 'categoryDescription': 'Pessoa', 'firstName':'FN','lastName':'Last Name','fiscalDocuments':[{'fiscalDocument':{'documentType':'Brasil: nº CPF','cpf':199999992}}],'gender':'M','emailAddress':'r****@*.com','optIns':[{'optIn':{'brandName':'consul','acceptanceStatus':false}},{'optIn':{'brandName':'brastemp','acceptanceStatus':true}}],'communicationData':[{'communicationInfo':{'addressId':'lalala','phoneNumbers':[{'phoneNumber':{'phoneType':'mobilePhone','phoneNumber':5555555555}}],'streetAddress':'ANY STREET','streetNumber':123,'streetComplement':null,'streetDistrict':'ANY TOWN','cityName':'ANY CITY','stateCode':'XX','zipCode':'12345','locationReferences':[{'locationReference':'Mercado'}],'countryCode':'ZZ'}},{'communicationInfo':{'addressId':2.563244E+7,'phoneNumbers':[{'phoneNumber':{'phoneType':'mobilePhone','phoneNumber':5555555555}},{'phoneNumber':{'phoneType':'homePhone','phoneNumber':555555555}}],'streetAddress':'ANY STREET','streetNumber':123,'streetComplement':'CASA','streetDistrict':'ANY TOWN','cityName':'ANY CITY','stateCode':'XX','zipCode':'12345','locationReferences':[{'locationReference':'Ao lado do deposito lua nova'}],'countryCode':'ZZ'}}]}"; 
    JToken token = JObject.Parse(jsonstring); 

    var firstname = token.SelectToken("firstName"); 
    tvfirst.Text = firstname.ToString(); 
    var lastname = token.SelectToken("lastName"); 
    tvlast.Text = lastname.ToString(); 
}; 

我用了两个TextView显示名字和姓氏项目,并使用一个按钮来解析json字符串。

并且通过拷贝你的JSON文件,似乎在你的JSON文件中的错误与节点addressId,你可以使用一些Json的格式来格式化你的JSON字符串,然后就可以看到这个问题。我将其改为“lalala”,以便在我的示例中进行测试。

+0

谢谢你这是有帮助的! –

首先你需要检查这是否是一个有效的json。根据我的分析,它有一些错误,如姓氏。您可以使用该网站来验证https://jsonformatter.curiousconcept.com/

此JSON是在一个陌生的方式构成的,而是由创建它拥有的所有对象,你可以使用它像这样:

using System; 
using System.Collections.Generic; 
using Newtonsoft.Json; 

namespace teste { 
    class MainClass { 
     public static void Main(string[] args) { 

      var jsonString = @"{'consumerId':56704292158, 'categoryId':1, 'categoryDescription': 'Pessoa', 'firstName':'FN','lastName':'Last Name','fiscalDocuments':[{'fiscalDocument':{'documentType':'Brasil: nº CPF','cpf':199999992}}],'gender':'M','emailAddress':'r * ***@*.com','optIns':[{'optIn':{'brandName':'consul','acceptanceStatus':false}},{'optIn':{'brandName':'brastemp','acceptanceStatus':true}}],'communicationData':[{'communicationInfo':{'addressId':'2****03','phoneNumbers':[{'phoneNumber':{'phoneType':'mobilePhone','phoneNumber':5555555555}}],'streetAddress':'ANY STREET','streetNumber':123,'streetComplement':null,'streetDistrict':'ANY TOWN','cityName':'ANY CITY','stateCode':'XX','zipCode':'12345','locationReferences':[{'locationReference':'Mercado'}],'countryCode':'ZZ'}},{'communicationInfo':{'addressId':'2.563244','phoneNumbers':[{'phoneNumber':{'phoneType':'mobilePhone','phoneNumber':5555555555}},{'phoneNumber':{'phoneType':'homePhone','phoneNumber':555555555}}],'streetAddress':'ANY STREET','streetNumber':123,'streetComplement':'CASA','streetDistrict':'ANY TOWN','cityName':'ANY CITY','stateCode':'XX','zipCode':'12345','locationReferences':[{'locationReference':'Ao lado do deposito lua nova'}],'countryCode':'ZZ'}}]}"; 

      JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings { 
       NullValueHandling = NullValueHandling.Ignore, 
       MissingMemberHandling = MissingMemberHandling.Ignore 
      }; 

      Pessoa pessoa = JsonConvert.DeserializeObject<Pessoa>(jsonString, jsonSerializerSettings); 

      Console.WriteLine(pessoa.FirstName); 
      Console.WriteLine(pessoa.LastName); 
     } 
    } 

    public class Pessoa { 
     public long ConsumerId { get; set; } 
     public int CategoryId { get; set; } 
     public string CategoryDescription { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public List<FiscalDocumentData> FiscalDocuments { get; set; } 
     public string Gender { get; set; } 
     public string EmailAddress { get; set; } 
     public List<OptInData> OptIns { get; set; } 
     public List<CommunicationData> CommunicationData { get; set; } 
    } 

    public class OptInData { 
     public OptInInfo OptIn { get; set; } 
    } 

    public class OptInInfo { 
     public string BrandName { get; set; } 
     public bool AcceptanceStatus { get; set; } 
    } 

    public class FiscalDocumentData { 
     public FiscalDocumentInfo FiscalDocument {get; set; } 
    } 

    public class FiscalDocumentInfo { 
     public string DocumentType { get; set; } 
     public long Cpf { get; set; } 
    } 

    public class CommunicationData { 
     public CommunicationInfo CommunicationInfo { get; set; } 
    } 

    public class CommunicationInfo { 
     public string AddressId { get; set; } 
     public List<PhoneInfo> PhoneNumbers { get; set; } 
     public string StreetAddress { get; set; } 
     public int StreetNumber { get; set; } 
     public string StreetComplement { get; set; } 
     public string StreetDistrict { get; set; } 
     public string CityName { get; set; } 
     public string StateCode { get; set; } 
     public string ZipCode { get; set; } 
     public List<Reference> LocationReferences { get; set; } 
     public string CountryCode { get; set; } 
    } 

    public class Reference { 
     public string LocationReference { get; set; } 
    } 

    public class PhoneInfo { 
     public PhoneNumberInfo PhoneNumber { get; set; } 
    } 

    public class PhoneNumberInfo { 
     public string PhoneType { get; set; } 
     public long PhoneNumber { get; set; } 
    } 
} 
+0

谢谢你的男人! –