Muflix
Muflix

Reputation: 6768

How to convert object into json array without property names

For this class

class Customer {
  public string FirstName {get; set;}
  public string LastName {get; set;}
}

I have collection

List<Customer> customers

When returning to browser client

return new JsonResult(new
{
                data = customers
});

The client get

{"data":[{"firstName":"Johny","lastName":"Johnson"}]}

Is there some way to get

{"data":[{"Johny","Johnson"}]}

without doing foreach like

var output = new List<string[]>();
foreach (var r in customers)
{
     output.Add(new string[] {
          r.FirstName,
          r.LastName
     });
}

?

Upvotes: 1

Views: 2483

Answers (2)

Adrian
Adrian

Reputation: 8597

You could add another property in the Customer object,

public string[] FullName {get { return new string[]{FirstName, LastName}; } } 

Decorate your Firstname and LastName properties with [JsonIgnore] so they don't get serialized.

Final product would look like so

public class Customer{

    [JsonIgnore]
    public string FirstName{get;set;}
    [JsonIgnore]
    public string LastName{get;set;}
    [JsonProperty("data")]
    public string[] FullName {get { return new string[]{FirstName, LastName}; } } 

    public Customer(string FirstName, string LastName){
        this.FirstName = FirstName;
        this.LastName = LastName;
    }
}

public static void Main(string[] args)
{
    Customer c = new Customer("Adrian", "i6");

    Console.Write(JsonConvert.SerializeObject(c));
}

This of course won't return exactly the desired result, if you wanted to completely remove the property you'll have to override the JsonWrite method inside JsonConverter however that would cause the JSON to be invalid of course as the JSON object requires a key:value property.

DotNetFiddle runnable of the above.

Upvotes: 3

Jacob
Jacob

Reputation: 78850

If you want some sort of "automatically derive a table from an array of JSON objects" functionality that's general across any data type, the algorithm would be to:

  1. Iterate over the array, collecting newly-encountered property names into a list as you go into column names. This is the only way to get all property names since it may not be guaranteed that all objects have the same properties in JSON.
  2. Create a list for each object in the list
  3. Map each object's property value into the list index of the column corresponding to the property name

This will give you two output artifacts: the column listings and the values by index. If you are safe assuming that the first object has the same properties as all the other objects in the Array, then you can avoid iterating over the entire collection for the first step. This is untested, but hopefully you get the gist.

using System.Collections.Generic;
using Newtonsoft.Json.Linq;

// ...

var payload = JObject.Parse(rawJson);
var dataArray = payload["data"] as JArray;
var firstItem = dataArray[0] as JObject;
var columns = firstItem.Properties().Select(prop => prop.Name).ToList();
var rows = (
    from obj as JObject in dataArray
    select columns.Select(col => obj[col]).ToList()
).ToList();

Upvotes: 1

Related Questions