Carmax
Carmax

Reputation: 2927

Is it possible to create this JSON format using a c# class?

I'm struggling with multiple image uploads in redactor. Specifically, creating the return JSON after uploading and saving the images.

I have managed to do it using StringBuilder, but i would like to do it in a properly typed class if possible, using return Json(redactorResult, JsonRequestBehavior.AllowGet);


Desired Format

From the redactor demo page, I can see the formatting I require is:

{
    "file-0": {
        "url":"/tmp/images/b047d39707366f0b3db9985f97a56267.jpg",
    "   id":"70e8f28f4ce4a338e12693e478185961"
    },
    "file-1":{
        "url":"/tmp/images/b047d39707366f0b3db9985f97a56267.jpg",
        "id":"456d9b652c72a262307e0108f91528a7"
    }
}

C# Class

But to create this JSON from a c# class I think I would need something like this :

public class RedactorFileResult
{
     public string url {get;set;}
     public string id {get;set;}
}

public class RedactorResult
{
    public RedactorFileResult file-1 {get;set;}
    public RedactorFileResult file-2 {get;set;}
    // .. another property for each file...
}

... which seems impossible at worst (never know how many images will be uploaded), and a bit impractical at best.

Question

Am I approaching this correctly? Is there a way to do this that I'm not aware of?

Or am I better just sticking with string builder on this occasion?

Upvotes: 2

Views: 78

Answers (2)

Matheus Neder
Matheus Neder

Reputation: 149

Define item:

class Item 
{
    public string Url { get; set; }
    public string Id { get; set; }  
}

Then you should use a dictionary instead of RedactorResult class, like this:

var redactorResult = new Dictionary<string, Item>();
redactorResult["file-1"] = new Item(){ Url = "...", Id = "..." };
redactorResult["file-2"] = new Item(){ Url = "...", Id = "..." }; 

If you prefer RedactorResult class, you may extend the Dictionary:

class RedactorResult : Dictionary<string, Item>
{
    private int count = 0;

    public void Add(Item item) 
    {
        this[$"file-{count}"] = item;
        count++;
    }
}

Upvotes: 2

Aleks Andreev
Aleks Andreev

Reputation: 7054

Define a class for single item:

public class File
{
    public string Url { get; set; }
    public string Id { get; set; }
}

Then create your files like this:

var files = new List<File>();
files.Add(new File{Url = "tmp/abc.jpg", Id = "42"});
files.Add(new File {Url = "tmp/cba.jpg", Id = "24"});

Now you are able to get desired json output with linq query:

var json = JsonConvert.SerializeObject(files.Select((f, i) => new {f, i})
    .ToDictionary(key => $"file-{key.i}", value => value.f));

In my example result would be:

{
  "file-0":{
    "Url":"tmp/abc.jpg",
    "Id":"42"
  },
  "file-1":{
    "Url":"tmp/cba.jpg",
    "Id":"24"
  }
}        

Upvotes: 4

Related Questions