0

I have to create something like the below, a JSON string:

{
     "sync": {
          "email": "[email protected]",
          "first": "James",
          "last": "Dawson",
          "cell": "2120980989",
          "valueOfField": [
               {
                    "number": "1",
                    "content": "second"
               },
               {
                    "number": "10",
                    "content": "Y"
               }
               /* more as needed */
          ]
    }
}

I can do everything up to valueOfField.

Here is my code:

sync cu = new sync();
cu.first = "James";
cu.last = "Doe";
cu.email = "[email protected]";
cu.cell = "999-999-9999";
/*for (int i = 0; i < 2; i++)
{
    cu.valueOfField.Add("1", "106-93-0909");
    cu.valueOfField.Add("5", "12/3/1995");
}*/
string json = Newtonsoft.Json.JsonConvert.SerializeObject(new { sync = cu });
...
public class sync
{
    public string first;
    public string last;
    public string email;
    public string cell;
    /*public IDictionary<string, string> valueOfField;*/
}

I tried adding an IDictionary but that didn't work.

Can I get some help in creating the valueOfField.

1 Answer 1

1

you need another class for the valueOfs

public class ValueOf{
  public string number {get;set;}
  public string content {get;set;}
}

then

public class sync
{
    public string first;
    public string last;
    public string email;
    public string cell;
    public List<ValueOf> valueOfField = new List<ValueOf>();
}

now

   cu.valueOfField.Add(new ValueOf{
         Number="1", Content = "106-93-0909"
   });
   cu.valueOfField.Add(new ValueOf{
         Number = "5", Content = "12/3/1995"); 
   });
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you... The example topped off the answer! Appreciate it. IT all maks sense, drew a blank for a bit :) +1
I get a System.NullReferenceException: 'Object reference not set to an instance of an object.' error in those example... Don't I have to initialize the list?
@Si8 yes sorry see edit
I just did it during the population of values... but your works as well. Either or works. :)

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.