【问题标题】:Is it possible to create this JSON format using a c# class?是否可以使用 c# 类创建这种 JSON 格式?
【发布时间】:2018-08-26 13:01:13
【问题描述】:

我正在为redactor 中的多张图片上传而苦苦挣扎。具体来说,在上传和保存图像后创建返回 JSON。

我已经设法使用StringBuilder 做到这一点,但如果可能的话,我想在一个正确类型的类中做到这一点,使用return Json(redactorResult, JsonRequestBehavior.AllowGet);


所需格式

redactor demo page,我可以看到我需要的格式是:

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

C# 类

但是要从 c# 类创建这个 JSON,我想我需要这样的东西:

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...
}

...这在最坏的情况下似乎是不可能的(永远不知道会上传多少张图片),而且在最好的情况下有点不切实际。

问题

我的处理方法正确吗?有没有我不知道的方法?

或者在这种情况下我最好还是坚持使用字符串生成器?

【问题讨论】:

  • 可能会用到字典
  • 该链接没有显示任何关于 json 格式的信息。你能再检查一遍吗?我希望你是错的,创建顺序对象而不是数组是非常糟糕的 JSON 礼仪。
  • 字典 应该没问题。
  • @Crowcoder - 我觉得这很奇怪,但我不是专家。我刚刚尝试在演示页面上上传多张图片,并在开发工具中查看了返回的json

标签: c# json asp.net-mvc upload redactor


【解决方案1】:

为单个项目定义一个类:

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

然后像这样创建你的文件:

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"});

现在您可以使用 linq 查询获得所需的 json 输出:

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

在我的示例中,结果是:

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

【讨论】:

  • 非常感谢,这正是我需要了解并使其正常工作的信息。
【解决方案2】:

定义项目:

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

那么你应该使用字典而不是 RedactorResult 类,像这样:

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

如果你更喜欢 RedactorResult 类,你可以扩展 Dictionary:

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

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

【讨论】:

  • 谢谢你 Matteus - 感谢你的回答,Aleks 刚刚把你拉到了帖子里
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
相关资源
最近更新 更多