2014-02-20 33 views
0

我有一個JSON文件包含:AppendAllText產生無效JSON

[{ 
    "title":"Colors", 
    "text":"1. White 2. Blue 3. Red 4. Yellow 5. Green" 
}] 

如果我使用

string json = JsonConvert.SerializeObject(favecolors, Formatting.Indented); 
var jsonFile= Server.MapPath("~/App_Data/favecolors.json"); 
System.IO.File.AppendAllText(@jsonFile, ","+json); 

我可以追加JSON對象到文件導致:

[{ 
    "title":"Colors", 
    "text":"1. White 2. Blue 3. Red 4. Yellow 5. Green" 
}],{ 
    "title":"Colors", 
    "text":"1. White 2. Blue 3. Red 4. Yellow 5. Green" 
} 

這是無效的JSON,因爲右方括號在錯誤的地方。任何人都可以幫忙嗎?

+0

還需要諮詢? –

回答

0

如果你的文件的JSON格式將是始終不變的,在這種情況下,一個JSON數組與至少一個節點[{},{}]你能做到這

var jsonFile = Server.MapPath("~/App_Data/favecolors.json"); 
FileStream fs = new FileStream(@jsonFile, FileMode.Open, FileAccess.ReadWrite); 
fs.SetLength(fs.Length - 1); // Remove the last symbol ']' 
fs.Close(); 
string json = JsonConvert.SerializeObject(favecolors, Formatting.Indented); 
System.IO.File.AppendAllText(@jsonFile, "," + json + "]"); 

這不是最優雅解決方案,但它應該使你想要做的。注意:這個解決方案非常複雜,確保文件的內容以']'符號結尾,否則你應該這樣做:1)將文件讀入var,2)concat new json(正確安裝),3)用合併的json寫入文件。

0

你可以嘗試更通用的東西,而不是添加/刪除結尾括號。希望下面的例子符合你的需求。

[JsonObject] 
public class FavoriteColor 
{ 
    public FavoriteColor() 
    {} 

    public FavoriteColor(string title, string text) 
    { 
     Title = title; 
     Text = text; 
    } 

    [JsonProperty(PropertyName = "title")] 
    public string Title { get; set; } 

    [JsonProperty(PropertyName = "text")] 
    public string Text { get; set; } 
} 

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    // Append new objects to your file 
    private async Task Append() 
    { 
     // Read file content and deserialize 
     string content = await ReadAsync("json.txt"); 

     var colors = new List<FavoriteColor>(); 
     if (!string.IsNullOrWhiteSpace(content)) 
      colors.AddRange(JsonConvert.DeserializeObject<List<FavoriteColor>>(content)); 

     // Add your new favorite color! 
     var fav = new FavoriteColor("new", "new color"); 
     colors.Add(fav); 

     // Writo back to file 
     await WriteAsync("json.txt", JsonConvert.SerializeObject(colors)); 
    } 

    // Async read 
    private async Task<string> ReadAsync(string file) 
    { 
     if (!File.Exists(file)) 
      return null; 

     string content; 
     using (var fileStream = File.OpenRead(file)) 
     { 
      byte[] buffer = new byte[fileStream.Length]; 
      await fileStream.ReadAsync(buffer, 0, (int)fileStream.Length); 
      content = Encoding.UTF8.GetString(buffer); 
     } 
     return content; 
    } 

    // Async write 
    private async Task WriteAsync(string file, string content) 
    { 
     using (var fileStream = File.OpenWrite(file)) 
     { 
      byte[] buffer = (new UTF8Encoding()).GetBytes(content); 
      await fileStream.WriteAsync(buffer, 0, buffer.Length); 
     } 
    } 
}