skip to Main Content

I want to display the list of state and city from a column inside my database into two lookupedit.

The following is the list for state and city that I’ve put inside a column my sql server:

[
  { "State": "California", 
    "City": 
      ["Los Angeles", 
       "San Diego", 
       "San Francisco" 
      ]
   }, 
   { "State": "Texas", 
     "City": 
       ["Houston", 
        "San Antonio", 
        "Dallas"
       ]
    }
]

Here is my code

List<string> stateCities = new List<string>();
                DataTable dtStateCity = _DBSet.GetDataTable("SELECT * FROM StateCity", false, null);
                foreach (DataRow dr in dtStateCity.Rows)
                {
                    stateCities.Add(AESB.DataConvert.MyToString(dr["StateCity"]));
                    var dictionary = stateCities.Select(x => JsonConvert.DeserializeObject<Dictionary<string, object>>(x))
                     .ToDictionary(x => x["State"].ToString(), x => ((JArray)x["City"]).ToObject<List<string>>());

                    lookUpEditState.Properties.DataSource = dictionary;
                    lookUpEditState.Properties.ValueMember = "State";
                    lookUpEditCity.Properties.DataSource = dictionary;
                    lookUpEditCity.Properties.ValueMember = "City";
                    lookUpEditCity.CascadingOwner = lookUpEditState;
                }

i got this error:

Fail to setup: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
‘System.Collections.Generic.Dictionary`2[System.String,System.Object]’ because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path ”, line 1, position 1.

Any idea how can i fix this? Thank you

2

Answers


  1. You need to deserialize JSON using a class that matches its representation. In this case you have an array of objects that have a State and City property, so you could use this:

    var template = new [] { new { State = "", City = new string[] {} }};
    var array = JsonConvert.DeserializeAnonymousType(jsonText, template);
    

    You could then convert it to a dictionary if you really want:

    var dictionary = array.ToDictionary( x => x.State, y => y.City );
    

    …which will give you a Dictionary<string,string[]>.

    Login or Signup to reply.
  2. This works for me

      Dictionary<string, List<string>> dictionary = JArray.Parse(json)
                            .ToDictionary(ja => (string)ja["State"],ja => ja["City"]
                            .Select(i => (string)i).ToList());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search