PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 24, 2022

[FIXED] How to Convert Json list String to List in c#?

 July 24, 2022     arraylist, c#, json, json.net, list     No comments   

Issue

I need to convert a json list string to a C# list

My Model:

public class AddressModel
{
    public string StateCode { get; set; }
    public string CityCode { get; set; }
    public string PinCode { get; set; }
    public string Place { get; set; }
    public string Street { get; set; }
    public string DoorNo { get; set; }
    public string State { get; set; }
    public string City { get; set; }
    public string AddresDetails{ get; set; }
    
}

Json:

"[\n  {\n    \"input\": {\n      \"statecode\": 1,\n      \"citycode\": 12,\n      \"pincode\": \"123\",\n       \"addresdetails\": \"\"\n    },\n    \"output\": [\n      \n    ]\n  },\n  {\n    \"input\": {\n      \"statecode\": 2,\n      \"citycode\": 45,\n      \"pincode\": \"765\",\n        \"addresdetails\": \"\"\n    },\n    \"output\": [\n      \n    ]\n  }\n]";

I tried with DeserializeObject but it's not working

var model = JsonConvert.DeserializeObject(json);

I would like to convert this into a list . could someone help me with this?


Solution

you have to fix your classes

 List<Data>  data = JsonConvert.DeserializeObject<List<Data>>(json);

public partial class Data
{
    [JsonProperty("input")]
    public AddressModel Input { get; set; }

    [JsonProperty("output")]
    public List<Output> Output { get; set; }
}

public partial class AddressModel
{
    [JsonProperty("statecode")]
    public long Statecode { get; set; }

    [JsonProperty("citycode")]
    public long Citycode { get; set; }

    [JsonProperty("pincode")]
    
    public long Pincode { get; set; }

    [JsonProperty("addresdetails")]
    public string Addresdetails { get; set; }
}

public partial class Output
{
}

if you need just a list of input

 List<AddressModel> inputs = data.Select(d =>d.Input ).ToList();

 // or just using AddressModel

List<AddressModel> inputs = JArray.Parse(json).Select(d =>d["input"].ToObject<AddressModel>() ).ToList();


Answered By - Serge
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing