我使用C#和MySQL在asp.net中创建了webservice。我想从此服务返回多个值。我使用以下代码:
[WebMethod]
public string RegisterUserViaFacebook(string fbid, string fbmailid,string devicetype)
{
string success = "Already Registered";
string id="", name="";
if (!ExistsFBID(fbid))
{
name = GenerateUserName();
string password = generatePassword(10);
string insertUser = "Insert into tbl_userinfo(UserName,Password,Facebook_ID,Facebook_EmailID,DeviceType) values";
insertUser += "( '" + name + "' ,'" + password + "','" + fbid + "','" + fbmailid + "','" + devicetype + "' )";
con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(insertUser, con);
success = cmd.ExecuteNonQuery().ToString();
con.Close();
string getID = "SELECT UserID from tbl_userinfo where UserName='" + name + "' ";
con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand(getID, con);
id = cmd1.ExecuteScalar().ToString();
con.Close();
if (Convert.ToInt16(success) > 0)
{
SendMail(fbmailid, name, password);
success = "New User" ;
}
else
success = "Error in Insertion";
}
else
{
string getID1 = "SELECT UserID, UserName from tbl_userinfo where Facebook_ID='" + fbid + "' ";
con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd2 = new MySqlCommand(getID1, con);
MySqlDataReader info = cmd2.ExecuteReader();
while (info.Read())
{
id = info.GetString(0);
name = info.GetString(1);
}
con.Close();
}
string jsonString = JsonConvert.SerializeObject(success);
String finalString = "{\"USER IS\":";
finalString += jsonString;
finalString += "}";
string jsonString1 = JsonConvert.SerializeObject(id);
String finalString1 =finalString + "{\"ID IS\":";
finalString1 += jsonString1;
finalString1 += "}" ;
string jsonString2 = JsonConvert.SerializeObject(name);
String finalString2 = finalString1 + "{\"NAME IS\":";
finalString2 += jsonString2;
finalString2 += "}";
return finalString2;
}
但它返回单个字符串中的所有值。我希望将这些值单独返回为Succeess
,ID
和Name
。
我该怎么做?
答案 0 :(得分:8)
创建一个简单的类来保存Success,id和name并返回它的序列化实例。
public class RegistrationResult
{
public string Success { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
你可以这样做:
var result = new RegistrationResult { Success = success, Name = name, Id = id} ;
return JsonConvert.SerializeObject(success);
答案 1 :(得分:0)
您可能希望在JSON中返回单个对象。
return "{user: "+JsonConvert.SerializeObject(success)+", id: "+JsonConvert.SerializeObject(id)+", name: "+JsonConvert.SerializeObject(name)+"}";
Oded的答案也很好。它更清晰,但也需要额外的课程。