将 vb.net 字符串转换为 Json 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23759552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert vb.net String to Json Object?
提问by Nadeem
I am new in vb.net, I am developing a webservice. I want to send a response in a json object. I have only one string in response.
我是 vb.net 的新手,我正在开发一个网络服务。我想在 json 对象中发送响应。我只有一个字符串作为响应。
public string GetUser(String IMEI)
{
string msg = "";
string SQL1 = "Select Email from [Customer] where [Vehicle]='" + IMEI + "'";
DataTable dt = dbcom.GetDataTable(SQL1);
if (dt.Rows.Count > 0)
{
msg = dt.Rows[0]["Email"].ToString();
//CV(username, IMEI);
//vehiclechk(IMEI);
}
return msg;
}
This send xml string.
How we convert msgstring in to json.
这发送 xml 字符串。我们如何将msg字符串转换为 json。
回答by Holger Brandt
I guess there are two ways to do it. Since this is a simple string, you can just brute force it:
我想有两种方法可以做到。由于这是一个简单的字符串,您可以暴力破解它:
Dim jsonMsg = "{""msg"":""" & msg & """}"
A more sophisticated way is put it into a class and serialize it.
一种更复杂的方法是将其放入一个类中并对其进行序列化。
Public Class MyMessage
Public Property Msg As String
Public Sub New(myMsg as String)
Msg = myMsg
End Sub
End Class
Dim myMsg As New MyMessage(msg)
Dim serializer as new JavaScriptSerializer
Dim jsonMsg = serializer.Serialize(myMsg)
You need a reference to System.Runtime.CompilerServices.
您需要对 System.Runtime.CompilerServices 的引用。

