2010-05-14 58 views
6

我參與了一個I18N項目,並且有一個調用將我們的* .resx文件序列化爲JSON對象(無論出於何種原因)。ASP.NET * .resx序列化

我想知道的是:

  • 有沒有辦法讓所有的有效鍵列表對於給定的* .resx文件,這樣我們可以使用HttpContext.GetGlobalResourceObject搶令牌?
  • 如果這樣行不通,有沒有人想出一個聰明的解決方案呢?
+0

其中一個原因是,如果您要創建依賴JSON數據和AJAX調用的應用程序,則可能必須在JavaScript中生成本地化的html片段,而無需使用C#View文件。在這種情況下,具有resx數據的JSON對象是不可靠的。 – sonjz 2012-10-16 21:08:30

回答

8
Sub ReadRessourceFile() 
     ''#Requires Assembly System.Windows.Forms 
     Dim rsxr As System.Resources.ResXResourceReader = New System.Resources.ResXResourceReader("items.resx") 

     ''# Iterate through the resources and display the contents to the console.  
     Dim d As System.Collections.DictionaryEntry 
     For Each d In rsxr 
      Console.WriteLine(d.Key.ToString() + ":" + ControlChars.Tab + d.Value.ToString()) 
     Next d 

     ''#Close the reader. 
     rsxr.Close() 
    End Sub 

然後,你需要把它添加到一個序列化的詞典,然後你就可以使用System.Web.Extensions.dll

序列化JSON
Public Class JSONHelper 

Public Shared Function Serialize(Of T)(ByVal obj As T) As String 
    Dim JSONserializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer() 
    Return JSONserializer.Serialize(obj) 
End Function 

Public Shared Function Deserialize(Of T)(ByVal json As String) As T 
    Dim obj As T = Activator.CreateInstance(Of T)() 
    Dim JSONserializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer() 
    obj = JSONserializer.Deserialize(Of T)(json) 
    Return obj 
End Function 

End Class 

編輯:C#:

public void ReadRessourceFile() 
{ 
    //Requires Assembly System.Windows.Forms ' 
    System.Resources.ResXResourceReader rsxr = new System.Resources.ResXResourceReader("items.resx"); 

    // Iterate through the resources and display the contents to the console. '  
    System.Collections.DictionaryEntry d = default(System.Collections.DictionaryEntry); 
    foreach (DictionaryEntry d_loopVariable in rsxr) { 
     d = d_loopVariable; 
     Console.WriteLine(d.Key.ToString() + ":" + ControlChars.Tab + d.Value.ToString()); 
    } 

    //Close the reader. ' 
    rsxr.Close(); 
} 

和JSON幫手:

public class JSONHelper 
{ 

    public static string Serialize<T>(T obj) 
    { 
     System.Web.Script.Serialization.JavaScriptSerializer JSONserializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
     return JSONserializer.Serialize(obj); 
    } 

    public static T Deserialize<T>(string json) 
    { 
     T obj = Activator.CreateInstance<T>(); 
     System.Web.Script.Serialization.JavaScriptSerializer JSONserializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
     obj = JSONserializer.Deserialize<T>(json); 
     return obj; 
    } 

} 
+1

JFYI,絕大多數SO用戶都更瞭解C# – abatishchev 2010-12-21 09:42:06

+0

然後,大多數SO用戶學到了一些東西。 – 2010-12-21 14:53:26

+1

是的,「祕密」是使用內置的ResXResourceReader類。 – Greg 2010-12-21 14:56:43