2016-07-01 86 views
0

我想生成一個json字符串,但是 我做了什麼是錯誤的?爲什麼這個代碼引發未處理的異常VB.NET String.Format FormatException未處理

Public Function GenerateJsonString(doer As Integer, comment As String, id As Integer) As String 
    Dim jsonString As String = String.Format("{done_by:{0}, comment:{1}, request_id:{2}}", doer, comment, id) 
    Return jsonString 
End Function 

型「System.FormatException」未處理的異常出現在mscorlib.dll

其他信息:輸入字符串的不正確的格式。

+0

分享你的所有代碼 – Developer

+0

看到我的更新,我已經過去了我所有的功能代碼。 –

回答

2

的括號{中的String.Format所以你需要,如果你希望他們使用兩個支架輸出像這樣一個特殊字符:

Dim jsonString As String = String.Format("{{done_by:{0}, comment:{1}, request_id:{2}}}", 806, "comment", 16233) 

它輸出

{done_by:806, comment:comment, request_id:16233} 

這不是有效的JSON,因爲它缺少「-characters。因此,要糾正你可以做

Dim jsonString As String = String.Format("{{""done_by"":{0}, ""comment"":""{1}"", ""request_id"":{2}}}", 806, "comment", 16233) 

請注意,註釋是字符串,還需要「-characters in value」。

輸出是正確的JSON:

{"done_by":806, "comment":"comment", "request_id":16233} 

也有通過序列化要做到這一點更容易和更可靠的方法:

Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer 
Dim jsonString As String = serializer.Serialize(New With {.done_by = 806, .comment = "comment", .request_id = 16233}) 

如果您有類庫或Windows -Project它需要系統。 Web.Extensions引用您的項目。

祝你好運!

1

問題是你的文字中有大括號。撥打String.Format時,大括號用於指示佔位符,但在文本開頭處有一個開口大括號,末尾用大括號括起來。如果你希望這些文字括號包含,則必須進行轉義,即

"{{done_by:{0}, comment:{1}, request_id:{2}}}" 
+0

有幫助,它爲我工作。 –

+0

如果解決了您的問題,請點擊大號複選標記以接受答案。 – jmcilhinney

+0

這產生無效的json,註釋是字符串 – Esko