我试图将一个字符串放在get的json数组中,但JArray.Parse失败,因为该字符串首先不是一个有效的json对象。如何将逗号分隔的字符串转换为json?
输入就像
34520,63631,45628
代码如下;
public static string GetLocationInZips(string strZipCodes)
{
JArray jarrZipCodes = new JArray();
JObject response = new JObject();
try
{
jarrZipCodes = JArray.Parse(strZipCodes);
}
catch(Exception ex)
{
response["success"] = false;
response["error"] = "Failed to serialize zip code array, please check and try again";
response["exception"] = ex.ToString();
return response.ToString();
}
}
答案 0 :(得分:2)
不要使用JArray。使用JsonConvert.SerializeObject(strZipCodes.Split(','))
,因为您需要来自字符串数组的JSON数组。如果您无法使用JsonConvert
中的NewtonSoft.JSON
,请使用JavascriptSerializer
。
//Call below function like
var jsonZipCodes = GetLocationInZips("34520,63631,45628");
public static string GetLocationInZips(string strZipCodes)
{
string jarrZipCodes = string.Empty;
JObject response = new JObject();
try
{
// jarrZipCodes = JsonConvert.SerializeObject(strZipCodes.Split(','));
jarrZipCodes = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(strZipCodes.Split(','));
return jarrZipCodes;
}
catch (Exception ex)
{
response["success"] = false;
response["error"] = "Failed to serialize zip code array, please check and try again";
response["exception"] = ex.ToString();
return response.ToString();
}
}
答案 1 :(得分:0)
使用Json.net库进行此操作。您可以使用Split()
函数将值拆分为数组,以分别处理每个值。
然后使用JsonConvert.SerializeObject
转换为JSON。
请参阅Convert comma seperated string to json了解一个很好的例子
答案 2 :(得分:0)
您可以拆分字符串以获取数组并使用JArray.FromObject
,如下所示:
string testInput = "34520,63631,45628";
JArray array = JArray.FromObject(testInput.Split(','));
答案 3 :(得分:-1)
感谢下面的Amit是最终的解决方案。
public static string GetLocationInZips(string strZipCodes)
{
JArray jarrZipCodes = new JArray();
string jarrZipCode = string.Empty;
JObject response = new JObject();
jarrZipCode = JsonConvert.SerializeObject(strZipCodes.Split(','));
try
{
jarrZipCodes = JArray.Parse(jarrZipCode);
}
catch(Exception ex)
{
response["success"] = false;
response["error"] = "Failed to serialize zip code array, please check and try again";
response["exception"] = ex.ToString();
return response.ToString();
}