简体   繁体   中英

WCF Deserialize JSON String

I had edited my question :

How can i deserialize the JSON string shows below :

"{\"acctId\": \"Test10001\",\"amount\": 200,\"currency\": \"USD\",\"Code\": \"Test\",\"serialNo\": \"1234566789asdsad0\"}"

Please give suggestion how can I get the data by using this method or any other recommended method.

Suggesting you to use StreamWriter as below. Use this function and pass your string and return a the Stream which will give you the desired JSON Content

public static Stream GenerateStreamFromString(string s)
{
         MemoryStream stream = new MemoryStream();
         StreamWriter writer = new StreamWriter(stream);
         writer.Write(s);
         writer.Flush();
         stream.Position = 0;
         return stream;
}

The payload of your POST request seems to be in JSON format, so you should use a JSON parsing library to parse it, such as Json.NET . Then you would write something like:

JsonConvert.DeserializeObject<YourRequestObject>(res)

you can read Json string like this

dynamic stuff = JObject.Parse(res.ToString());

        string acctId= stuff.acctId;

But the response string you are parsing should be json formatted.

I think below code should serve your purpose:

    public class DeserializedData
    {
        public string acctId { get; set; }
        public string amount { get; set; }
        public string currency { get; set; }
        public string Code { get; set; }
        public string serialNo { get; set; }
    }    

StreamReader reader = new StreamReader(streamdata);
string res = reader.ReadToEnd();

Use third party dlls like Json.NET or Restsharp:

1.) Using Json.Net Json.NET

var result = JsonConvert.DeserializeObject<DeserializedData>(res);

2.) Using Restsharp Restsharp

var jsonDeserializer = new RestSharp.Deserializers.JsonDeserializer();
var response = jsonDeserializer.Deserialize<DeserializedData>(res);

Let me know if it doesn't work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM