How to separate JSON Data In ASP.NET Console Application? - asp.net

I Create a one web API. its main aim is a request to another server and get the response from that server.
I successfully get the response for a particular server.
I get the response(its a JSON Format) is below.
{
"id": "test#gmail.com",
"active": 1,
"is_logged": true,
"token": "hsja3t56yJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3RAZHZlby5jb20iLCJwYXNzd29yZCI6InRlc3QyMDE4KyIsImV4cGlyZU9uIjoiMjAxOS0wNi0yMVQwNTozNzowOC4xODhaIn0.3wgGeL_HvcoEJJeEF7tj8jeXk2uIKpOoi9ewmK5yhteh",
"status": "OK",
"usertype": "TestUser",
"msg": "Login Successfull."
}
I try to separate using split function
string[] sep = response.Split(',');
foreach (string any in sep)
Console.WriteLine(any);
//string[] colon = sep[0].Split(':');
string[][] colon = sep.Select(x => x.Split(':')).ToArray();
//int count = colon.Count();
for (int i = 0; i <= colon.Length; i++)
{
Console.WriteLine(colon[i][0]);
Console.WriteLine(colon[i][1]);
}
Any other way to separate the response? I also use all the field in some other purpose.

Create a Class based on your response property:
public class UserData
{
public string id { get; set; }
public int active { get; set; }
public bool is_logged { get; set; }
public string token { get; set; }
public string status { get; set; }
public string usertype { get; set; }
public string msg { get; set; }
}
On reading the response data, use JsonConvert.DeserializeObject
string response = "{\"id\":\"test #gmail.com\",\"active\":1,\"is_logged\":true,\"token\":\"hsja3t56yJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3RAZHZlby5jb20iLCJwYXNzd29yZCI6InRlc3QyMDE4KyIsImV4cGlyZU9uIjoiMjAxOS0wNi0yMVQwNTozNzowOC4xODhaIn0.3wgGeL_HvcoEJJeEF7tj8jeXk2uIKpOoi9ewmK5yhteh\",\"status\":\"OK\",\"usertype\":\"TestUser\",\"msg\":\"Login Successfull.\"}";
var responseData = JsonConvert.DeserializeObject<UserData>(response);
//here the print in JSON Data
Console.WriteLine("id : " + responseData.id);
Console.WriteLine("active : " + responseData.active);
Console.WriteLine("is_logged : " + responseData.is_logged);
Console.WriteLine("token : " + responseData.token);
Console.WriteLine("status : " + responseData.status);
Console.WriteLine("usertype : " + responseData.usertype);
Console.WriteLine("msg : " + responseData.msg);

use Newtonsoft.json.dll by adding the NuGet package,
Then convert the response to json object
JObject jo = JObject.Parse(searchCondition);
foreach (JToken child in jo.Children()) {
var prop = child as JProperty;
if (prop.Value != null && !string.IsNullOrEmpty(prop.Value.ToString())) {
string name=prop.Name;
string value = prop.Value;
//You can now do whatever with the values like put in a list of object
}
}

This is My own example to get the properties from JSON string, you can use this.
But first, you need to install this package:-> Newtonsoft.Json.Linq to access JObject
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string jsonString = "{\"firstname\":\"Alex Wu\",\"lastname\":\"type\"}";
JObject jObject = JObject.Parse(jsonString);
string firstname = (string)jObject.SelectToken("firstname");
string lastname = (string)
Console.WriteLine("{0}", firstname);
Console.ReadLine();
}
}

Related

Consuming web api with RestSharp basic authentication return null

I am trying to consume an endpoint with RestSharp with Basic authentication.
I followed the instructions on the documentation https://restsharp.dev/getting-started/getting-started.html
The request was successful but I think the request body was malformed.
How can I get this to work
internal BalanceInquiryResponse BalanceInquiryRest(BalanceInquiryRequest BalanceInquiryRequest, Settings Settings)
{
// BalanceInquiryResponse BalanceInquiryResponse = new BalanceInquiryResponse();
var client = new RestClient(Settings.BaseUrl + "All/Inquiry");
client.Authenticator = new HttpBasicAuthenticator(Settings.Username, Settings.Password);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(new
{
Acc = BalanceInquiryRequest.Acc
});
IRestResponse response = client.Execute(request);
IRestResponse<BalanceInquiryResponse> res = client.Execute<BalanceInquiryResponse>(request);
if (response.IsSuccessful)
{
BalanceInquiryResponse = new BalanceInquiryResponse
{
responseInquiry = res.Data.responseInquiry,
ResponseDescription = res.Data.ResponseDescription,
ResponseMessage = res.Data.ResponseMessage
};
return BalanceInquiryResponse;
}
else
{
BalanceInquiryResponse = new BalanceInquiryResponse
{
ResponseDescription = responseses.ErrorMessage,
};
return BalanceInquiryResponse;
}
}
This is my response body
{
"responseMessage": "Successful",
"responseDescription": "Request Successful",
"responseInquiry": null
}
When I tried with postman I got
{
"ResponseMessage": "Successful",
"ResponseDescription": "Request Successful",
"response": {
"AvalBal": 586324.42,
"ReverAmt": 0,
"AccCurrency": "US "
}
}
IRestResponse<BalanceInquiryResponse> res = client.Execute<BalanceInquiryResponse>(request);
So there is a specific reason...you are putting BalanceInquiryResponse in the generic IRestResponse above.
With the above call, this should automatically hydrate the BalanceInquiryResponse object, and you shouldn't need to hand map.
Aka, you should ~not~ need this below code:
BalanceInquiryResponse = new BalanceInquiryResponse
{
responseInquiry = res.Data.responseInquiry,
ResponseDescription = res.Data.ResponseDescription,
ResponseMessage = res.Data.ResponseMessage
};
I think your issue is that your POCO object (BalanceInquiryResponse) should perfectly match the "structure" of the JSON.
Change your BalanceInquiryResponse to PERFECTLY match the json "properties".
and recognize you have a nested object.
I think it it would be:
public class ResponsePoco {
public double AvalBal { get; set; }
public int ReverAmt { get; set; }
public string AccCurrency { get; set; }
}
public class BalanceInquiryResponse{
public string ResponseMessage { get; set; }
public string ResponseDescription { get; set; }
public ResponsePoco response { get; set; }
}
Pay attention the to "ResponsePoco response"..note the variable name is LOWERCASE .. because...the json has a lowercase "response" in it.
I have called the (child) object "ResponsePoco" to highlight the difference between the object name and the variable name.
If you cannot "perfectly" match the Poco properties. you can use attributes to "massage" the discrepencies. As seen here:
https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm
public class Videogame
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("release_date")]
public DateTime ReleaseDate { get; set; }
}

asp.net parse json array

I write this code for read json in httphandler:
var jsonSerilizer = new JavaScriptSerializer();
var jsonString = String.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
and my json string is:
{"r_id":"140","name":"d","count":"5","c_id":"150"}
and i use this method for parse json string:
JavaScriptSerializer j = new JavaScriptSerializer();
dynamic a = j.Deserialize(jsonString, typeof(object));
string r_id = a["r_id"];
string Name = a["name"];
string count = a["count"];
string c_id = a["c_id"];
up code parse my json string to :
r_id:140
name:d
count:5
c_id:50
When client send me array of string json for example :
{"r_id":"140","name":"d","count":"5","c_id":"150"}
{"r_id":"150","name":"der","count":"50","c_id":"150"}
i can parse up json string
How can i?
I use this code:
var jsonSerilizer = new JavaScriptSerializer();
var jsonString = String.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
File.AppendAllText(#"d:\status\LOL.txt", "GetJSON to FROM:"+ jsonString+"\r\n", Encoding.UTF8);
JavaScriptSerializer j = new JavaScriptSerializer();
dynamic a = j.Deserialize(jsonString, typeof(List<ClientMessage>));
foreach (var obj in a)
{
File.AppendAllText(#"d:\status\LOL.txt", obj.name + "\r\n", Encoding.UTF8);
}
but when program recieve to File.AppendAll.. program crash and down.
First of all try to create a model ( class to hold your objects) like this :
Class ClientMessage {
public string r_id {get;set;}
public string name {get;set;}
public string count {get;set;}
public string c_id {get;set;}
}
In this case you would receive a List , so try to do it like this :
JavaScriptSerializer j = new JavaScriptSerializer();
dynamic a = j.Deserialize(jsonString, typeof(List<ClientMessage>));
// and then iterate on your object
foreach (var obj in a)
{
//start assigning values
}
I would suggest creating an object you can parse your JSON into, so something like:
public MyClass {
public int r_id { get; set;}
public string name { get; set; }
// etc
}
This will allow you to parse directly into that object, like this:
var results = j.Deserialize<List<MyClass>>(jsonString);
Can you try something this code, I am assuming you are getting json data like below.
[
{
r_id: "123",
name: "deepu",
count:"5",
c_id:"150"
},
{
r_id: "444",
name: "aaa",
count:"25",
c_id:"55"
},
{
r_id: "5467",
name: "dfgdf",
count:"5",
c_id:"3434"
}
]
I am using the above Client Message class here and adding JsonProperty attribute.
public class ClientMessage
{
[JsonProperty("r_id")]
public string RId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("count")]
public string Count { get; set; }
[JsonProperty("c_id")]
public string Cid { get; set; }
}
Finally, get the json data fort testing, I am reading the data from external file..
var data = System.IO.File.ReadAllText("jsondata.txt");
var jsResult = JsonConvert.DeserializeObject<List<ClientMessage>>(data);
NOTE : You need to add Newtonsoft.Json reference in your project

How to show the JSON data in asp.net web form

I am Beginner at Asp.net so can anyone plz help me to show the data provided in the below shown JSON Api in Asp.net Step by Step.It be of great help if this is answered.
http://fantasy.premierleague.com/web/api/elements/180/
A good way to use Json in C# is with Json.NET
JSON.NET - Official site will help you work with it.
Example to use it
public class User {
public User(string json) {
JObject jObject = JObject.Parse(json);
JToken jUser = jObject["user"];
name = (string) jUser["name"];
teamname = (string) jUser["teamname"];
email = (string) jUser["email"];
players = jUser["players"].ToArray();
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
// Use
private void Run() {
string json = #"{""user"":{""name"":""asdf"",
""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}

How to read dynamic rss feed

In my application i will have dynamic rss feed url saved by users. so i want to know that how can i read that xml which will be returned by rss feed. what will be the structure of that xml ? I have reviewed some feed url and i noticed that most of them have title and description tags but i am not sure to this. if i get these two tags then i will parse xml but if they are not always available then how can i parse xml in that case.
these two contains title and description tag
http://rss.news.yahoo.com/rss/entertainment
http://xml.weather.yahoo.com/forecastrss?p=USCA1116
At first you need to read a XML file for that I recommend you to use XPath or Linq to XML, and as you already said there are three main elements that make up a feed; "title", "link" and "description".
Not a very long time ago I wrote a code to do that, I hope this works for you.
I created this two entities.
public class RssFeed
{
public string Title { get; set; }
public string Link { get; set; }
public string Description { get; set; }
public string PubDate { get; set; }
public string Language { get; set; }
public ObservableCollection<RssItem> RssItems { get; set; }
}
public class RssItem
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
}
Then on this method I read every element from the XML file by using Linq to XML
private static void ReadFeeds()
{
string uri = #"http://news.yahoo.com/rss/entertainment";
WebClient client = new WebClient();
client.DownloadStringAsync(new Uri(uri, UriKind.Absolute));
client.DownloadStringCompleted += (s, a) =>
{
if (a.Error == null && !a.Cancelled)
{
var rssReader = XDocument.Parse(a.Result);
var feed = (from rssFeed in rssReader.Descendants("channel")
select new RssFeed()
{
Title = null != rssFeed.Descendants("title").FirstOrDefault() ?
rssFeed.Descendants("title").First().Value : string.Empty,
Link = null != rssFeed.Descendants("link").FirstOrDefault() ?
rssFeed.Descendants("link").First().Value : string.Empty,
Description = null != rssFeed.Descendants("description").FirstOrDefault() ?
rssFeed.Descendants("description").First().Value : string.Empty,
PubDate = null != rssFeed.Descendants("pubDate").FirstOrDefault() ?
rssFeed.Descendants("pubDate").First().Value : string.Empty,
Language = null != rssFeed.Descendants("language").FirstOrDefault() ?
rssFeed.Descendants("language").First().Value : string.Empty
}).Single();
var rssFeeds = (from rssItems in rssReader.Descendants("item")
select new RssItem()
{
Title = null != rssItems.Descendants("title").FirstOrDefault() ?
rssItems.Descendants("title").First().Value : string.Empty,
Link = null != rssItems.Descendants("link").FirstOrDefault() ?
rssItems.Descendants("link").First().Value : string.Empty,
Description = null != rssItems.Descendants("description").FirstOrDefault() ?
rssItems.Descendants("description").First().Value : string.Empty,
}).ToList();
feed.RssItems = new ObservableCollection<RssItem>(rssFeeds);
}
};
}
And finally you have your feed to be displayed wherever you want.

JsonResult equivalent to [DataMember(Name="Test")]

I have a method doing this:
public JsonResult Layar(string countryCode, string timestamp, string userId,
string developerId, string layarName, double radius,
double lat, double lon, double accuracy)
{
LayarModel model = new LayarModel(lat, lon, radius);
return Json(model, JsonRequestBehavior.AllowGet);
}
It returns this object:
public class LayarModel
{
private List<HotSpot> _hotSpots = new List<HotSpot>();
public List<HotSpot> HotSpots { get { return _hotSpots; } set { _hotSpots = value; } }
public string Name { get; set; }
public int ErrorCode { get; set; }
public string ErrorString { get; set; }
}
I want the JSON to be
{"hotspots": [{
"distance": 100,
"attribution": "The Location of the Layar Office",
"title": "The Layar Office",
"lon": 4884339,
"imageURL": http:\/\/custom.layar.nl\/layarimage.jpeg,
"line4": "1019DW Amsterdam",
"line3": "distance:%distance%",
"line2": "Rietlandpark 301",
"actions": [],
"lat": 52374544,
"type": 0,
"id": "test_1"}],
"layer": "snowy4",
"errorString": "ok",
"morePages": false,
"errorCode": 0,
"nextPageKey": null
}
Everything comes out capitalised as in the class being returned (HotSpots instead of hotspots).
I have tried DataContract and DataMembers(Name="Test") but that doesn't work. Any suggestions?
JsonResult() uses JavaScriptSerializer internally for serialization, and it seems it doesn't support defining the serialized property names using attributes.
DataContractJsonSerializer supports this, so that may be a way to go.
Some links that may be useful:
JavaScriptSerializer.Deserialize - how to change field names : JavaScriptSerializer.Deserialize - how to change field names
DataContractJsonSerializer Versus JavaScriptSerializer : Changing Field Names: http://publicityson.blogspot.com/2010/06/datacontractjsonserializer-versus.html
I would also recommend installing json.NET but the rest is a lot easier. Below is an extension method I am using in my current application to provide better reuse, feel free to adapt it to your needs, but it should do what you need right out of the box.
public class JsonNetResult : ActionResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult()
{
SerializerSettings = new JsonSerializerSettings
{
//http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
#if DEBUG
Formatting = Formatting.Indented, //Makes the outputted Json easier reading by a human, only needed in debug
#endif
ContractResolver = new CamelCasePropertyNamesContractResolver() //Makes the default for properties outputted by Json to use camelCaps
};
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{
JsonTextWriter writer = new JsonTextWriter(response.Output) {Formatting = Formatting};
JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
}
public static class JsonNetExtenionMethods
{
public static ActionResult JsonNet(this Controller controller, object data)
{
return new JsonNetResult() {Data = data};
}
public static ActionResult JsonNet(this Controller controller, object data, string contentType)
{
return new JsonNetResult() { Data = data, ContentType = contentType };
}
public static ActionResult JsonNet(this Controller controller, object data, Formatting formatting)
{
return new JsonNetResult() {Data = data, Formatting = formatting};
}
}
Here's an example of using it.
public JsonNetResult Layar(string countryCode, string timestamp, string userId,
string developerId, string layarName, double radius,
double lat, double lon, double accuracy)
{
LayarModel model = new LayarModel(lat, lon, radius);
return this.JsonNet(model);
}
The part to note that solves your problem specifically is when the ContractResolver on the JsonSerializerSettings is set to use new CamelCasePropertyNamesContractResolver()
This way you never have to set custom naming again.

Resources