0
"fields": [
   {
       "field": {
            "name": "SMS",
            "value": "Yes"
       }
   },
   {
       "field": {
            "name": "Email",
            "value": ""
        }
    },
    {
        "field": {
            "name": "Total",
            "value": ""
        }
    },
]

I have tried to form the JSON format like above, so i formed the class like below. While serialization it does not return expected form, how can i achieve this one.

public class Test
{
    public List<Field> fields;
}
public class Field
{
    public string name { get; set; }
    public string value { get; set; }
}

Response:

"fields": [{
                "name": "SMS",
                "value": "Yes"
            }, {
                "name": "Email",
                "value": ""
            },{
                "name": "Total",
                "value": ""
            }]
2
  • Are you opposed to using newtonsoft.com/json? Commented Jul 16, 2017 at 15:00
  • I can't understand quite clearly. Are you saying that - you had some input string -> serialized to array of objects through JSON.Net -> which on deserialization doesn't give back the original string. Is it? Commented Jul 16, 2017 at 15:03

3 Answers 3

3

Use this website http://json2csharp.com and generate all the classes automatically. Just copy-paste your json there.

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

Comments

1

You can customize resulting JSON object with anonymous types and LINQ. Please try this code:

var test = new Test {fields = new List<Field>()};
test.fields.Add(new Field {name = "f1", value = "v1"});
test.fields.Add(new Field {name = "f2", value = "v2"});

var json = JObject.FromObject(new { fields = test.fields.Select(f => new {field = f}).ToArray() })
    .ToString();

A json variable would be:

{
  "fields": [
    {
      "field": {
        "name": "f1",
        "value": "v1"
      }
    },
    {
      "field": {
        "name": "f2",
        "value": "v2"
      }
    }
  ]
}

Comments

0

You just missed a class level:

public class Test
{
    public List<FieldHolder> fields;
}

public class FieldHolder
{
    public Field field { get; set; }
}

public class Field
{
    public string name { get; set; }
    public string value { get; set; }
}

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.