3

I have the following code, I want the end to be JSON that a JQuery autocomplete can read.

[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static string GetNames(string prefixText, int count)
{        
     Trie ArtistTrie = (Trie)HttpContext.Current.Cache["CustomersTrie"];

     List<string> list = ArtistTrie.GetCompletionList(prefixText, 10);
     Dictionary<string, string> dic = new Dictionary<string, string>();
     foreach (string a in list)
     {
         dic.Add(a, "name");
     }
    string json = JsonConvert.SerializeObject(dic, Formatting.Indented);
    return json;

 }

The JSON looks like this:

  {
     "the album leaf": "name",
     "the all-american rejects": "name",
     "the allman brothers band": "name",
     "the animals": "name",
     "the antlers": "name",
     "the asteroids galaxy tour": "name",
     "the avett brothers": "name",
     "the band": "name",
     "the beach boys": "name",
     "the beatles": "name"
  }

This is backwards, I want

    "name" : "the allman brothers"

but.... the dictionary needs a unique key, and identical values are ok,

What is an easy fix for this , also is this readable from JQuery?

2
  • Reverse how you're adding to the dictionary. dic.Add("name", a); instead of dic.add(a, "name"); Commented Jan 22, 2014 at 23:54
  • You can't just reverse it; dictionary requires unique keys, so you cannot repeatedly add "name". Reguarding the OP's assertion that "This is backwards"... NO, it's not. That's how a dictionary of key/value pairs is represented in JSON. It's simpler to just do string json = JsonConvert.SerializeObject(list.Select(x => new {name = x}), Formatting.Indented);. That generates and serializes a set of anonymous objects that just have a 'name' property. No need to declare explicit type names. Commented Jan 31, 2017 at 19:19

2 Answers 2

3

An easy fix for this is NOT to use a dictionary and instead use a custom data object, possibly with one property:

class Album
{
  public string Name{get;set;}
}

Now you can Serialize/Deserialize a list of this custom class.

 string json = JsonConvert.SerializeObject(YourListOfAlbum, Formatting.Indented);   

             

Sign up to request clarification or add additional context in comments.

Comments

3

You can't have a dictionary with multiple keys using the same string "name" because the second one will overwrite the value of the first one. Instead you'll need to create an array of objects like:

[
  {"name": "the allman brothers"},
  {"name": "the beach boys"}
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.