sangram parmar
sangram parmar

Reputation: 8736

Want to Serialize in specific format

i want to serialize list object in following format.

  1. without square bracket []at start and end
  2. without commma , it should be in new line.

    {"document_id":37577,"document_name":"Office Marketview........} {"document_id":37578,"document_name":"Office Marketview........} {"document_id":37579,"document_name":"Office Marketview........} {"document_id":37580,"document_name":"Office Marketview........} {"document_id":37581,"document_name":"Office Marketview........}

currently i am using

var jsoncontent = JsonConvert.SerializeObject(publicationClasses, Formatting.None);

No idea. I google it, but not found any solution.

Upvotes: 0

Views: 59

Answers (1)

Balázs
Balázs

Reputation: 2939

You could serialize each object independently and then perform a simple string-concat:

string result = string.Join(
    Environment.NewLine,
    publicationClasses.Select(obj => JsonConvert.SerializeObject(obj, Formatting.None))
);

Use \n instead of Environment.NewLine if you so desire.

And then you can return the result as described in this question as so:

return Content(result, "text/plain");

You can use the mimetype of your preference as required. Note that this is only a one-go solution, as mentioned in the comment section by Amit Kumar Ghosh, if this is something you need to be doing over and over all over the place then a custom media type formatter is the way to go (in fact, in order to adhere to the Web API practices, you should use a custom media formatter either way). However, this code provides the logic of it, you just need to perform the refactorings as necessary.

Upvotes: 1

Related Questions