locked
C# get response from an api get method RRS feed

  • Question

  • User-1950594959 posted

    Hi, I am working on getting a response back from an api and save stream as json document. Using the below C# code which makes use of  JavaScriptSerializer I get the response back and save stream as json document. But, the response has a datetime field which is coming out differently.

    C#:

            string json = string.Empty;
            string cities;
            cities = getCities(); //json payload
    
            JavaScriptSerializer oJS = new JavaScriptSerializer
            City[] Cities = oJS.Deserialize<City[]>(cities); //deserialize and then serialize to save json document
    
            json = oJS.Serialize(Cities);
            using (StreamWriter sw = new StreamWriter(File.Create(@"C:\temp\cities.json")))
            {
                sw.Write(json);
            }

    json output file:

    [
    {"DateTime":"\/Date(1587782790077)\/"},
    {"DateTime":"\/Date(1587782790107)\/"}      
    ]

    Expected Output:

    [
    {"DateTime":"2002-08-17T09:27:07.042"},
    {"DateTime":"1978-03-19T06:43:29.013"}      
    ]

    Please guide me to fix this.

    Thank you.

    Thursday, July 23, 2020 6:34 PM

All replies

  • User-474980206 posted

    You should use the newtonsoft json library rather than the obsolete JavaScriptserializer (which can not be updated due to backward compatibility, and ms stopped updating after they switched to newtonsoft)

    Friday, July 24, 2020 1:57 AM
  • User-1950594959 posted

    Hi Bruce, Thanks very much for your response. Made changes to code using newtonsoft. But I get results with slash "\".

    NewtonSoft:

            string json = string.Empty;
            string cities;
            cities = getCities(); //json payload
    
            json = JsonConvert.SerializeObject(cities);
            using (StreamWriter sw = new StreamWriter(File.Create(@"C:\temp\cities.json")))
            {
                sw.Write(json);
            }

    cities.json:

    [
    {\"id\":2643743,
     \"name\":"London"},
    {\"id\":2643744,
     \"name\":"Manchester"}
    ]

    Expected Result:

    [
    {"id":2643743,
     "name":"London"},
    {"id":2643744,
     "name":"Manchester"}
    ]

    Friday, July 24, 2020 4:57 AM
  • User-1950594959 posted

    Hi Bruce, After modifying code Deserialize and Serialize it works as expected. Not sure if this is a slick way of doing it.

            cities = getCities(); //json payload
    	City[] Cities = JsonConvert.DeserializeObject<City[]>(cities);
            json = JsonConvert.SerializeObject(Cities);

    Thank you

    Friday, July 24, 2020 5:28 AM
  • User-474980206 posted

    it is odd that getCities returns a JSON string, rather than C# objects.

    Wednesday, July 29, 2020 3:21 PM