4

I'm supposed to out a list of settings in JSON, which I get from a database and store in a Tuple<string, string>.

I was able to print it, but it's not displaying like it should:

[{
    "Item1": "setting1Name",
    "Item2": "setting1Value"
 }, {
    "Item1": "testt",
    "Item2": "testt"
 }, {...
 }]

The output should be:

[
  {"setting1Name":"setting1Value"},
  {"setting2Name":"setting2Value"},{...}
]

How do I serialize a Tuple as JSON?

Controller:

[GET("Settings")]
public async Task<ActionResult> Settings(string userKey)
{             
    if ((await UserManager.FindByIdAsync(userKey)) == null)
        return new HttpUnauthorizedResult();                        

    List<Tuple<string, string>> settings = new List<Tuple<string, string>>();

    var userSettings = settingRepository.Get(new Guid(userKey));

    for (int i = 0; i < userSettings.Count; i++)
    {
        var tuple = Tuple.Create<string, string>(
            userSettings[i].Name.ToString(),
            userSettings[i].Value.ToString()
            );
        settings.Add(tuple);                
    }                      
        return Json(settings,JsonRequestBehavior.AllowGet);
}

Database repository method:

public List<Setting> Get(Guid userId)
{
    return _context.Settings.Where(s => s.UserId == userId).ToList();
}
George Stocker
  • 57,289
  • 29
  • 176
  • 237
Gloumy
  • 63
  • 1
  • 6
  • Could you show us your view? I think you want to go 1 level deeper, using a loop. – Max Mar 25 '14 at 14:58
  • It's for an API, we're not using a view for now, i'm testing with Rest Console – Gloumy Mar 25 '14 at 15:02
  • It is because of the way Tuple is serialized, check this: http://stackoverflow.com/questions/16101115/how-does-a-tuple-serialize-to-and-deserialize-from-json – Jportelas Mar 25 '14 at 15:02
  • Check this out, it might help: http://forums.asp.net/t/1821729.aspx?JsonMediaTypeFormatter+does+not+work+with+Tuple+int+List+string+ – Jportelas Mar 25 '14 at 15:06
  • Well, gotta say i don't fully understand it .. I'll take a look again tonight, after a little rest, it may be easier. But anyway, thank you – Gloumy Mar 25 '14 at 15:34

1 Answers1

1

You could play with something like this

Replace this line

return Json(settings,JsonRequestBehavior.AllowGet);

With

var dict = new Dictionary<string, string>();
settings.ForEach(a => dict.Add(a.Item1, a.Item2));           
return Json(new List<Dictionary<string, string>>{dict}, 
       JsonRequestBehavior.AllowGet);
Kunukn
  • 2,136
  • 16
  • 16