-2

I have a C# app, that has an object, that looks like this:

public class MyObject
{
  public int Id { get; set; }
  public int ParentId { get; set; }
  public string Name { get; set; }
  ...
}

I then get a list of objects like this:

var myObjects = MyObject.LoadAll();

I need to create a JSON object that looks like this:

{ "1":"James", "2":"Bill", "3":"Andrew" }

1, 2, and 3 are the Id values of the list of MyObject entities. "James", "Bill", and "Andrew" are the values of the "Name" property from each object. How do I create a JSON object in this manner using just the two properties?

Thank you!

keenthinker
  • 7,645
  • 2
  • 35
  • 45
xam developer
  • 1,923
  • 5
  • 27
  • 39
  • 3
    Although your requested JSON is valid as JSON, it's a very poor choice as a serialized object (because it doesn't represent a serialized object... at all). Any control over what is needed? – Erik Philips Apr 14 '15 at 19:29
  • Try http://json2csharp.com/ just copy/paste your json and it will create your classes and properties for you. – Jacob Roberts Apr 14 '15 at 19:29
  • 1
    You shouldn't be creating a json like that. – Praveen Paulose Apr 14 '15 at 19:30
  • 2
    @ShiftySituation VS's Paste-Special-JSON As Classes will do that for you – Ňɏssa Pøngjǣrdenlarp Apr 14 '15 at 19:30
  • 1
    The JSON example you posted isn't wise, as it is not a representation of what you're saying you want it to be. What you have shown is an object with 3 numbered properties whose values are the corresponding names. What you should be looking for is `[ {"Id":1, "Name":"James"}, {"Id":2, "Name":"Bill"}, {"Id":3, "Name":"Andrew"} ]`. This actually makes sense, and is able to be easily parsed from a C# object. Otherwise, you're going to have to create a custom serializer and it gets a LOT messier. – krillgar Apr 14 '15 at 19:31
  • 1
    Have a look at [Json.NET](http://www.newtonsoft.com/json). – keenthinker Apr 14 '15 at 19:33
  • 2
    xam developer, See how your classmate deserializes it http://stackoverflow.com/questions/29632593/parsing-json-key-value-pairs-with-json-net – L.B Apr 14 '15 at 19:37

1 Answers1

1

You can use linq and Json.Net library for that.

var myObjects = MyObject.LoadAll();
var forSerialization = myObjects.ToDictionary(x => x.Id, x => x.Name);
var json = JsonConvert.SerializeObject(forSerialization);
Pavel Bakshy
  • 7,697
  • 3
  • 37
  • 22