0

I have an object Person like this:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
}

I tried to create a list like this:

 var personList = new List<object>();
 personList.Add(new Person { Address = "addr1", Age = 20, Name = "Person1" });
 personList.Add(new Person { Address = "addr2", Age = 22, Name = "Person2" });
 personList.Add(new Person { Address = "addr3", Age = 25, Name = "Person1" });

 var jsonString = JsonConvert.SerializeObject(personList);

This is the result of jsonString

[{"Name":"Person1","Age":20,"Address":"addr1"},

{"Name":"Person2","Age":22,"Address":"addr2"},

{"Name":"Person1","Age":25,"Address":"addr3"}]

Below is my expected result, so how can I do that?

{
    Person1:{"Name":"Person1","Age":20,"Address":"addr1"},

    Person2:{"Name":"Person2","Age":22,"Address":"addr2"},

    Person3:{"Name":"Person3","Age":25,"Address":"addr3"}
}
Hoang Tran
  • 886
  • 3
  • 13
  • 32
  • You wont get Person1, Person2, types unless you have individual properties for those. Are there always going to be 3 person objects? I'm assuming the list is dynamic – d.moncada Oct 25 '17 at 01:51
  • Ya, this list is dynamic and it will have more than 3 people. – Hoang Tran Oct 25 '17 at 01:52

2 Answers2

1

You have to use a Dictionary<string, Person> when I am not that wrong. This should serialize it that way, you want it.

You can add the Attribute [JsonIgnore] to Name optionally, if you don't want redundant data.

Edit: You can serialize a list directly to a dictionary by using a custom JsonConverter: Newtonsoft.Json serialize collection (with indexer) as dictionary

Teneko
  • 1,417
  • 9
  • 16
-1
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
    // constructor
    public Person(string name, int age, string address){
        this.Name = name;
        this.Age = age;
        this.Address = address;
    }
 }

then

 List<person>People = new List<person>();
 People.Add(new Person("name1", 1, "address1"));
 People.Add(new Person("name2", 2, "address2"));
 People.Add(new Person("name3", 3, "address3"));


string jsonString = JsonConvert.SerializeObject(People);

then on the client, omitting the part about getting it to the client

var people = JSON.parse(jsonString)
Bindrid
  • 3,655
  • 2
  • 17
  • 18
  • You are answering to the question. That way you can serialize, but the resulted json string is the same as the topic writer is getting falsely. – Teneko Oct 25 '17 at 02:04