Click here to Skip to main content
15,896,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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\"}]"}


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();

        }
Posted
Updated 17-Jul-17 1:40am
v2

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);
 
Share this answer
 
Comments
dattaprasaddhuri 17-Jul-17 7:50am    
tried but not working.
giving following error:
Newtonsoft.Json.dll but was not handled in user code

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WebApplication1.test]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<t>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Path 'SearchDocumentResult', line 1, position 24.
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);


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.
 
Share this answer
 
Comments
dattaprasaddhuri 17-Jul-17 8:48am    
Not working
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:

C#
var myTest = Movie m = JsonConvert.DeserializeObject<test[]>(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:

C#
var searchResult = JObject.Parse(json).SearchDocumentResult; //dynamic but gets string
//then you can deserialize that:
var myTest = Movie m = JsonConvert.DeserializeObject<List<test>>(json);
 
Share this answer
 
v2
Comments
dattaprasaddhuri 17-Jul-17 6:17am    
I had tried this but i am getting following error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'WebApplication1.test[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<t>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'SearchDocumentResult', line 1, position 24.
Andy Lanng 17-Jul-17 6:37am    
I have updated the solution. Sorry I don't have time to fully test >_<

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900