如何将json字符串转换为列表? [英] How to convert the json string into list?
问题描述
我在我的c#应用程序中使用了其余的post服务,该应用程序发送了jsonstring结果。我想将该结果转换为列表,但它给出了错误。
输出字符串: -
I am consuming the rest post service in my c# application which sends the jsonstring result. I want to convert that result into the list but it is giving error.
Output String:-
{"SearchDocumentResult":"[{\"ContextType\":\"ddd\",\"ContextIDPrimary\":\"TestContextP\",\"ContextIDSecondary\":\"TestContextS\",\"ContextIDTertiary\":\"\",\"RequirementID\":\"17\",\"Source\":\"image\",\"DocumentName\":\"4.pdf\",\"DocumentImage\":\"\",\"ErrorCode\":\"0\",\"ErrorDescription\":\"\",\"createdBy\":\"\",\"createdDate\":\"12-07-2017 15:39:57\"},{\"ContextType\":\"ddd\",\"ContextIDPrimary\":\"TestContextP\",\"ContextIDSecondary\":\"TestContextS\",\"ContextIDTertiary\":\"\",\"RequirementID\":\"18\",\"Source\":\"image\",\"DocumentName\":\"4.pdf\",\"DocumentImage\":\"\",\"ErrorCode\":\"0\",\"ErrorDescription\":\"\",\"createdBy\":\"\",\"createdDate\":\"12-07-2017 15:42:07\"}]"}
我得到了以上输出为json字符串。我无法将上面的字符串转换为List。任何人都可以指导我这个。
我尝试过:
I am getting above output as json string . I am unable to convert above string to List. Can anyone guide me on this.
What I have tried:
public class test
{
public string ContextType { get; set; }
public string ContextIDPrimary { get; set; }
public string ContextIDSecondary { get; set; }
public string ContextIDTertiary { get; set; }
public string Source{get;set;}
public string DocumentID { get; set; }
}
public class JsonHelper
{
/// <summary>
/// JSON Serialization
/// </summary>
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// <summary>
/// JSON Deserialization
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
}
public class RootObject
{
// public List<SearchDocumentResult> SearchDocumentResult { get; set; }
public IEnumerable<SearchDocumentResult> SearchDocumentResult { get; set; }
//public List<Person> People1 { get; set; }
}
protected void Button1_Click(object sender, EventArgs e)
{
test t = new test
{
ContextType = "ddd",
ContextIDPrimary = "",
ContextIDSecondary = "",
ContextIDTertiary = " ",
Source = "",
DocumentID = ""
};
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(test));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, t);
string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
string result = webClient.UploadString("http://192.168.0.151:222/Service1.svc/SearchDocument", "POST", data);
var result11 = JsonHelper.JsonDeserialize<RootObject1>(result);
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//serializer.MaxJsonLength = Int32.MaxValue;
// var a = serializer.Deserialize(result, typeof(object));
// string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"},{\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}";
//// var result11 = JsonHelper.JsonDeserialize<RootObject1>(json);
// var firstNames = result11.People.Select(p => p.FirstName).ToList();
// var lastNames = result11.People.Select(p => p.LastName).ToList();
}
推荐答案
查找 Newtonsoft [ ^ ]。这几天它几乎是行业标准。
用NuGet获取它。互联网上有大量的指令,但这里有如何使用它:
Look up Newtonsoft[^]. It's pretty much industry standard these days.
Get it with NuGet. There are loads of instructions all over the interwebs, but here's how to use it:
var myTest = Movie m = JsonConvert.DeserializeObject<test[]>(json);
您可以甚至只是反序列化为动态对象,但创建自己的类总是更好,就像您已经完成的那样
更新:公平点,这不适用于上面的json开箱即用。
你可以反序列化一个数组,但你必须反序列化为一个List对象。
第一个问题是你的json包含一个json子字符串。您必须首先反序列化:
You "can" even just deserialize into a dynamic object, but it's always better to create your own classes, just as you have done
UPDATE: fair point, this won't work out of the box with the json above.
You can deserialise an array but you have to deserialize into a List object.
The first issue is that your json contains a json sub-string. You will have to deserialize this first:
var searchResult = JObject.Parse(json).SearchDocumentResult; //dynamic but gets string
//then you can deserialize that:
var myTest = Movie m = JsonConvert.DeserializeObject<List<test>>(json);
它取决于结果中的内容。如果它只是JSON,那么你需要反序列化为List< test>因为它代表的是一组测试对象。<br />
It depends what is in "result". If it is just the JSON then you need to deserialise to a List<test> as it represents is an array of test objects.
string result = "[{\"ContextType\":\"ddd\",\"ContextIDPrimary\":\"TestContextP\",\"ContextIDSecondary\":\"TestContextS\",\"ContextIDTertiary\":\"\",\"RequirementID\":\"17\",\"Source\":\"image\",\"DocumentName\":\"4.pdf\",\"DocumentImage\":\"\",\"ErrorCode\":\"0\",\"ErrorDescription\":\"\",\"createdBy\":\"\",\"createdDate\":\"12-07-2017 15:39:57\"},{\"ContextType\":\"ddd\",\"ContextIDPrimary\":\"TestContextP\",\"ContextIDSecondary\":\"TestContextS\",\"ContextIDTertiary\":\"\",\"RequirementID\":\"18\",\"Source\":\"image\",\"DocumentName\":\"4.pdf\",\"DocumentImage\":\"\",\"ErrorCode\":\"0\",\"ErrorDescription\":\"\",\"createdBy\":\"\",\"createdDate\":\"12-07-2017 15:42:07\"}]";
var result11 = JsonHelper.JsonDeserialize<List<test>>(result);
如果结果有了它周围的xml,你需要使用类似XmlDocument的东西从XML中提取JSON然后按照上面的方式执行。
If "result" has the xml around it you'll need to use something like XmlDocument to extract the JSON from the XML then do as above.
尝试这样的事情。
try something like this.
var testString={"SearchDocumentResult":"[{\"ContextType\":\"ddd\",\"ContextIDPrimary\":\"TestContextP\",\"ContextIDSecondary\":\"TestContextS\",\"ContextIDTertiary\":\"\",\"RequirementID\":\"17\",\"Source\":\"image\",\"DocumentName\":\"4.pdf\",\"DocumentImage\":\"\",\"ErrorCode\":\"0\",\"ErrorDescription\":\"\",\"createdBy\":\"\",\"createdDate\":\"12-07-2017 15:39:57\"},{\"ContextType\":\"ddd\",\"ContextIDPrimary\":\"TestContextP\",\"ContextIDSecondary\":\"TestContextS\",\"ContextIDTertiary\":\"\",\"RequirementID\":\"18\",\"Source\":\"image\",\"DocumentName\":\"4.pdf\",\"DocumentImage\":\"\",\"ErrorCode\":\"0\",\"ErrorDescription\":\"\",\"createdBy\":\"\",\"createdDate\":\"12-07-2017 15:42:07\"}]"};
var result = JsonConvert.DeserializeObject<List<test>>(json);
这篇关于如何将json字符串转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!