user5016413
user5016413

Reputation:

Getting property name while converting Json from Object in C#

I have a class like below:

public class PCBulkRequest 
{ 
    public List<PCRequest> pcRequest { get; set; } 
}

When I'm trying to convert this class to a JSON string I'm getting JSON with the property name included, which I don't want.

string json = JsonConvert.SerializeObject(pcRequest, Formatting.Indented);

Result :

{
  "pcRequest": [
    {
      "name": "John",
      "surname": "Elton"
    },
    {
      "name": "John",
      "surname": "Elton"
    }
  ]
}

Expected result:

[
  {
    "name": "John",
    "surname": "Elton"
  },
  {
    "name": "John",
    "surname": "Elton"
  }
]

Upvotes: 0

Views: 187

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503479

Just serialize the list directly:

string json = JsonConvert.SerializeObject(pcRequest.pcRequest, Formatting.Indented);

As an aside, your naming is slightly confusing at the moment - it sounds like you have a variable called pcRequest that's of type PCBulkRequest, and your pcRequest property sounds like it should be a single request when it's actually a list. I'd have names something like this:

public class PCBulkRequest
{
    public List<PCRequest> Requests { get; set; }
}

...

var bulkRequest = GetBulkRequest(); // Wherever this comes from
string json = JsonConvert.SerializeObject(bulkRequest.Requests, Formatting.Indented);

Upvotes: 3

ADyson
ADyson

Reputation: 62074

We can't see how you defined it, but based on the result you're getting it seems that pcRequest in your code must be an instance of the PCBulkRequest class.

Therefore Json.NET will serialise the entire object, as you instructed it to. If you only want to serialise the list, then it's quite simple: you need to supply the list from within that object as the item to be serialised.

string json = JsonConvert.SerializeObject(pcRequest.pcRequest, Formatting.Indented);

The Json.NET library can only serialise what you tell it to, it can't guess which sub-section you actually wanted serialising!


N.B. I would suggest maybe naming your variables more clearly so that you don't re-use the name of a property within the class as a variable name for an instance of that class. It can get a bit confusing. And the property name pcRequest is singular, so it sounds like it would hold a single request, when in fact it's a list - that can also get confusing. Your code will be much more maintainable and understandable (both for you and for others) if you take the time to give your variables meaningful, clear names.

Upvotes: 3

Related Questions