WCF Deserialize JSON String - c#

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)

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.

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.

Related

Read specific object data from json

I want to get specific object data from json from url the following code give me. i need the second object 'EmailAddressSuffices'
WebRequest request = WebRequest.Create(
"https://atea-dev.accesscontrol.windows.net/v2/metadata/IdentityProviders.js?protocol=wsfederation&realm=https%3a%2f%2flocalhost%3a44300%2fAccount%2fLoginCallback%2f&reply_to=https%3a%2f%2flocalhost%3a44300%2fAccount%2fLoginCallback%2f&context=&request_id=&version=1.0&callback=");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Using JSON.Net you can deserialize the JSON response easily:
Solution 1
1. Create a class to map your JSON into:
public class ResponseObject
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("LoginUrl")]
public string LoginUrl { get; set; }
[JsonProperty("LogoutUrl")]
public string LogoutUrl { get; set; }
[JsonProperty("ImageUrl")]
public string ImageUrl { get; set; }
[JsonProperty("EmailAddressSuffixes")]
public IList<string> EmailAddressSuffixes { get; set; }
}
2. Deserialize your JSON using JsonConvert.Deserialize<ResponseObject>()
var myresponse = JsonConvert.DeserializeObject<List<ResponseObject>>(responseFromServer);
string email = myresponse[1].EmailAddressSuffixes[0];
Solution 2
If you don't want to bother with derializing the entire thing then you can do this:
JArray array = JArray.Parse(responseFromServer);
string q = array[1]["EmailAddressSuffixes"][0].ToString();
But you should make sure that your object has the right format (and the right number of items in the array.

Windows App - Using XML in textbox

[DataContract]
public class RootObject
{
[DataMember]
public int RecipeID { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public string Cuisine { get; set; }
[DataMember]
public string Category { get; set; }
[DataMember]
}
public async static Task<RootObject> GetRecipe()
{
var http = new HttpClient();
var url = String.Format("http://api.bigoven.com/recipe/196149?api_key=//apikey");
var response = await http.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
XmlSerializer serializer = new XmlSerializer(typeof(RootObject));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
XmlReader reader = XmlReader.Create(ms);
RootObject i;
i = (RootObject)serializer.Deserialize(reader);
return i;
}
I use the above method in a bigoven class which gets the data of a recipe as XML data such as:
<Recipe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<RecipeID>196149</RecipeID>
<Title>Lasagna</Title>
<Cuisine>Italian</Cuisine>
and I would like to put the data for the title and cuisine into textboxes, however when I try the method below I get the error "Recipe xmlns='' was not expected."
RootObject myRecipe = await bigoven.GetRecipe();
textBox.Text = myRecipe.Title;
Answered before. Basically this:
When serialising an XML document to a .NET string, the encoding must be set to UTF-16. Strings are stored as UTF-16 internally, so this is the only encoding that makes sense. If you want to store data in a different encoding, you use a byte array instead.
See the entire thread here:
Using StringWriter for XML Serialization
It looks like your Json serializer might be trying to deserialize xml data.
You might try looking at the raw string in result and making sure that it's actually JSON data. If it's not, you need to find the appropriate deserailizer to use.
I'm guessing result contains XML in which case you'd need to use an XML Deserializer to convert it to a RootObject
Here's the link for the .NET one:
https://msdn.microsoft.com/en-us/library/tz8csy73(v=vs.110).aspx

Easiest way to parse JSON response

Is there any easy way to parse below JSOn in c#
{"type":"text","totalprice":"0.0045","totalgsm":"1","remaincredit":"44.92293","messages": [
{"status":"1","messageid":"234011120530636881","gsm":"923122699633"}
]}
and in case Multiple results.
Follow these steps:
Convert your JSON to C# using json2csharp.com;
Create a class file and put the above generated code in there;
Add the Newtonsoft.Json library to your project using the Nuget Package Manager;
Convert the JSON received from your service using this code:
RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
(Feel free to rename RootObject to something more meaningful to you. The other classes should remain unchanged.)
You can safely use built-in JavaScriptSerializer without referencing additional third party libraries:
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
ser.DeserializeObject(json);
I found a way to get it without using any external API
using (var w = new WebClient())
{
var json_data = string.Empty;
string url = "YOUR URL";
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var result = jsSerializer.DeserializeObject(json_data);
Dictionary<string, object> obj2 = new Dictionary<string, object>();
obj2=(Dictionary<string,object>)(result);
string val=obj2["KEYNAME"].ToString();
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
}
For me ... the easiest way to do that is using JSON.net do a deserialize to a entity that represents the object, for example:
public class Message
{
public string status { get; set; }
public string messageid { get; set; }
public string gsm { get; set; }
}
public class YourRootEntity
{
public string type { get; set; }
public string totalprice { get; set; }
public string totalgsm { get; set; }
public string remaincredit { get; set; }
public List<Message> messages { get; set; }
}
And do this:
YourRootEntity data JsonConvert.DeserializeObject<YourRootEntity>(jsonStrong);

c# Json to object list

I have a function that accesses a API and retrieves some Json values, these values are returned and pasted into a rich textbox. How am I able to convert this Json into a object list? The internet is filled with what i am asking but i'm not getting any wiser after reading and trying it all.
This is the function, URL is the Api link that retrieves the Json.
public string GetApi(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
This is the Json structure
{"id":19684,"buys":[{"listings":10,"unit_price":94,"quantity":2498},{"listings":42,"unit_price":93,"quantity":10398},{"listings":139,"unit_price":92,"quantity":34501},{"listings":8,"unit_price":91,"quantity":1939},{"listings":38,"unit_price":90,"quantity":9270},{"listings":7,"unit_price":89,"quantity":1266},{"listings":43,"unit_price":88,"quantity":10565},{"listings":23,"unit_price":87,"quantity":5476},{"listings":80,"unit_price":86,"quantity":19827},
The first order of business is to use a library to parse the JSON. For this answer I use Newtonsoft.Json, one of the most used JSON libraries for .NET.
Then, the structure of the document you receive from the server should be identified. I'm just guessing here, but I assume it's something like the classes defined below. The JsonProperty is an attribute to specify the field name from the JSON document mapping to the property. It isn't necessary to specify this, only when your property names are different from the field names in the JSON document. In this case, unit_price does not match the standard .NET PascalCase naming convention for properties.
public class Listings
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
public List<Buy> Buys { get; private set; }
public Listings()
{
Buys = new List<Buy>();
}
}
public class Buy
{
[JsonProperty(PropertyName = "listings")]
public int Listings { get; set; }
[JsonProperty(PropertyName = "unit_price")]
public int UnitPrice { get; set; }
[JsonProperty(PropertyName = "quantity")]
public int Quantity { get; set; }
}
Once you have defined the class structure, you can let the library do all of the work. Look into the documentation for more details, here is how you would retrieve the list inside the method you already wrote.
public Listings GetApi(string url)
{
...
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<Listings>(jsonReader);
}
...
}

Deserializing JSON to List<> is not working in C#

This is the JSON i got from stream, and converted to string.
"{\"data\":[{\"thread_id\":\"1111155552222\",\"recipients\":[123123,456456],\"message_count\":2100},{\"thread_id\":\"1111155553333\",\"recipients\":[123124,456457],\"message_count\":4851},{\"thread_id\":\"1111155554444\",\"recipients\":[123125,456458],\"message_count\":435}]}"
public class DataContainer
{
List<data> data { get; set; }
}
public class data
{
public string thread_id { get; set; }
public long[] recipients { get; set; }
public int message_count { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
DataContainer data = ser.Deserialize<DataContainer>(json);
I am getting null at data, it does not seem to get deserialize. amateur in json. getting headache with this already.
Thanks!
Getting the JSON string
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader reader = new StreamReader(stream, encode);
string json = reader.ReadToEnd();
It seems your "JSON you got from stream and converted to string" has been serialized twice.
ASP.NET automatically JSON serializes your service methods’ responses, even if their result is an object or collection of objects
You should be able to use it directly without having to serialize/deserialize it.
Something like:
//Assuming GetJson() returns a JSON string, which you can use directly
DataContainer data = GetJson();
Check this: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/
Also this: Reading from JSON, data not displayed

Categories