public static string GetJsonValue(string jsonStr, string key) { string result = string.Empty; if (!string.IsNullOrEmpty(jsonStr)) { key = "\"" + key.Trim('"') + "\""; int index = jsonStr.IndexOf(key) + key.Length + 1; if (index > key.Length + 1) { //先截逗号,若是最后一个,截“}”号,取最小值 int end = jsonStr.IndexOf(',', index); if (end == -1) { end = jsonStr.IndexOf('}', index); } result = jsonStr.Substring(index, end - index); result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格 } } return result; }
--上面的不规范,参考下面写法
public static String GetJsonValue(String jsonStr, String key){
String result ="";
if (!jsonStr.equals("")){
key = "\"" + key.trim() + "\"";
int index = jsonStr.indexOf(key) + key.length() + 1;
if (index > key.length() + 1){
//先截逗号,若是最后一个,截“}”号,取最小值
int end = jsonStr.indexOf(',', index);
if (end == -1){
end = jsonStr.indexOf('}', index);
}
String result ="";
if (!jsonStr.equals("")){
key = "\"" + key.trim() + "\"";
int index = jsonStr.indexOf(key) + key.length() + 1;
if (index > key.length() + 1){
//先截逗号,若是最后一个,截“}”号,取最小值
int end = jsonStr.indexOf(',', index);
if (end == -1){
end = jsonStr.indexOf('}', index);
}
result = jsonStr.substring(index, end - index);
result = result.trim(); //过滤引号或空格
}
}
return result;
}
result = result.trim(); //过滤引号或空格
}
}
return result;
}
public static string GetXMLstrByKey(string Key, XmlDocument xml) { object strValue = xml.SelectSingleNode("xml").SelectSingleNode(Key).InnerText; if (strValue != null) { return strValue.ToString(); } else { return ""; } }