从img lib制作一个JSON文件

时间:2017-01-17 08:05:02

标签: c# angularjs json

我试图制作一个.JSON文件,我可以在我的angularjs项目中使用。我希望后端自动将站点更新为img文件夹中的内容。

我所做的是:

首先我搜索文件夹中的所有项目:

    public static String[] GetFilesFrom(String searchFolder, String[] filters, bool isRecursive)
    {
        List<String> filesFound = new List<String>();
        var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
        foreach (var filter in filters)
          {
            filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
          }
        return filesFound.ToArray();
    }

将其保存到数组:

String searchFolder = @"images\galleri";
var filters = new String[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp" };
files = GetFilesFrom(searchFolder, filters, false);

尝试将其写入JSON

       var _data = new Dictionary<string, string> {};

        for (int i = 0; i < files.Length; i++)
        {
            _data = new Dictionary<string, string>
         {
                { "img", files[i] }
         };
        }
        string json = JsonConvert.SerializeObject(_data.ToArray());
        System.IO.File.AppendAllText(@"\js\json.json", json);

这给了我输出:

[
  {
    "Key":"img",
    "Value":"images\\galleri\\placeholder.png"
  }
]

数组“files”确实包含多个图片,“files”中的所有路径都是正确的。为什么它只显示数组中的最后一项?我知道“for”语句是错误的,我如何添加到字典而不用写相同的密钥和保存的previus 我如何让它以JSON格式显示全部:

[
 {
   "img": "images\\galleri\\placeholder.png"
 },
 {
   "img": "images\\galleri\\img1.png"
 },
 {
   "img": "images\\galleri\\img2.png"
 }
]  

2 个答案:

答案 0 :(得分:1)

创建一个您将序列化的类Image

public class Image
{
   [JsonProperty("img")]
   public string ImagePath {get; set;}
}

你的for循环将如下所示:

List<Image> images = new List<Image>();
for (int i = 0; i < files.Length; i++)
{
   Image img = new Image() {ImagePath = files[i]};
   images.Add(img);
}

string json = JsonConvert.SerializeObject(images);

答案 1 :(得分:1)

阅读完你的评论之后我才明白问题不仅仅是序列化,第一个问题是每次都输入相同的密钥。所以我想出了List<KeyValuePair<string, string>>而不是new Dictionary<string, string>。现在它看起来像这个

string[] files = { "placeholder.png", "img1.png", "img2.png" }; //Just Entered Dummy Data for test
List<KeyValuePair<string, string>> _data = new List<KeyValuePair<string, string>>();
for(int i = 0; i < files.Length; i++)
{
    _data.Add(new KeyValuePair<string, string>("img", files[i]));
}
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.Converters.Add(new KeyValuePairJsonConverter());
jss.NullValueHandling = NullValueHandling.Ignore;
jss.Formatting = Formatting.Indented;
string json = JsonConvert.SerializeObject(_data, jss);

我们还需要KeyValuePairJsonConverter像这样

public class KeyValuePairJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        List<KeyValuePair<string, string>> list = value as List<KeyValuePair<string, string>>;
        writer.WriteStartArray();
        foreach(var item in list)
        {
            writer.WriteStartObject();
            writer.WritePropertyName(item.Key.ToString());
            writer.WriteValue(item.Value.ToString());
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<KeyValuePair<string, string>>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var jsonObject = JObject.Load(reader);
        var target = Create(objectType, jsonObject);
        serializer.Populate(jsonObject.CreateReader(), target);
        return target;
    }

    private object Create(Type objectType, JObject jsonObject)
    {
        if(FieldExists("Key", jsonObject))
        {
            return jsonObject["Key"].ToString();
        }

        if(FieldExists("Value", jsonObject))
        {
            return jsonObject["Value"].ToString();
        }
        return null;
    }

    private bool FieldExists(string fieldName, JObject jsonObject)
    {
        return jsonObject[fieldName] != null;
    }
}

,输出将是

Screenshot of JSON