How to parse JSON object using C# - c#

I want to post data to the database where I am fetching the data in a JSON format.
Here is the following JSON string:
"[{"cph_id":"67/123/7894","phone_no":"0000623019"},
{"cph_id":"69/213/1234","phone_no":"0000623019"}]"
I have also created the following classes:
public class RootObject
{
public List<dlregistrationdata> data { get; set; }
}
public class dlregistrationdata
{
public string cph_id[] { get; set; }
public string phone_no[] { get; set; }
}
I try to deserialize using the following command:
try
{
var obj = JsonConvert.DeserializeObject<List<dlregistrationdata>>(result);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.61.25.30/CPRestApi/api/user/register");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (email != null)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
dynamic arr = new JObject();
for (int i = 0; i < obj.Count; i++)
{
arr.cph_id = obj[i].cph_id;
arr.user_name = email;
arr.user_phone_number = obj[i].phone_no;
arr.user_password = password;
arr.status = 1;
arr.name = name;
}
streamWriter.Write(arr);
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpResponse.StatusCode == System.Net.HttpStatusCode.Created)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result1 = streamReader.ReadToEnd();
}
return RedirectToLocal("Index");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ViewBag.ErrorMessage = "User Already Registered";
ModelState.AddModelError("", "User Already Registered");
return View(model);
}
But I am getting the error:
"converting value "67/123/7894" to type 'System.String[]'. Path '[0].cph_id', line 1, position 24"
Any help will be highly appreciated.
Thank You!

Changes made in model class:
public class dlregistrationdata
{
public string cph_id { get; set; }
public string phone_no { get; set; }
}
public class RequestRegistrationAPI {
public string user_name { get; set; }
public string user_password { get; set; }
public string user_phone_number { get; set; }
public string name { get; set; }
public int status { get; set; }
public string[] cph_id { get; set; }
}
Changes made in code:
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
List<string> cphid = new List<string>();
string phone_no = "";
foreach (dlregistrationdata data in obj)
{
cphid.Add(data.cph_id);
phone_no = data.phone_no;
}
RequestRegistrationAPI request = new RequestRegistrationAPI();
request.user_name = email;
request.user_password = password;
request.user_phone_number = phone_no;
request.name = name;
request.cph_id = cphid.ToArray();
request.status = 1;
streamWriter.Write(JsonConvert.SerializeObject(request));
}
This works perfectly for me.

change classes to :
public class dlregistrationdata
{
public string cph_id { get; set; }
public string phone_no { get; set; }
}
now change code to :
var obj = JsonConvert.DeserializeObject<List<dlregistrationdata>>(result);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.61.25.30/CPRestApi/api/user/register");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (email != null)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
dynamic arr = new JObject();
for (int i = 0; i < obj.Count; i++)
{
arr.cph_id = obj[i].cph_id;
arr.user_name = email;
arr.user_phone_number = obj[i].phone_no;
arr.user_password = password;
arr.status = 1;
arr.name = name;
}
streamWriter.Write(arr);
}
}

Related

How to Deserialize json Object on gridview?

I am building C# windows form that accessing json data. I want to make it display on gridview.
How can I DeserializeObject the json data on gridview?
Sorry for newbie here.
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public IList<Namedata> namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
string username = "myuser";
string password = "myuserpass";
byte[] byteArray = Encoding.UTF8.GetBytes("{\"name\":\"" + Name.Text + "\",\"id\":\"1\"}");
WebRequest request = WebRequest.Create("http://myservice/Service4.svc/s_name");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)));
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream = request.GetResponse().GetResponseStream();
var result = (new StreamReader(stream).ReadLine());
JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = result;
}
here are json data:
{
"s_name": {
"ResultCode": 1,
"ResultName": "Found",
"namedatas": [
{
"PeopleName": "Jane",
"PeopleAge": "20",
"PeopleSurname": "Jade"
},
{
"PeopleName": "Newton",
"PeopleAge": "18",
"PeopleSurname": "Handy"
},
{
"PeopleName": "Java",
"PeopleAge": "21",
"PeopleSurname": "Handy"
}
]
}
}
You are not giving the gridview the correct source. Try this,
var data = JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = data.s_name.namedatas;
Base on the information, here is a potential solution:
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public Namedata[] namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
HttpClient _client = new HttpClient();
string username = "myuser";
string password = "myuserpass";
var byteArray = System.Text.Encoding.ASCII.GetBytes($"{username}:{password}");
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
dynamic content = new ExpandoObject();
content.name = Name.Text;
content.id = 1;
var json = Newtonsoft.Json.JsonConvert.SerializeObject(content);
var data = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = _client.PostAsync("http://myservice/Service4.svc/s_name", data).Result;
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Example>(response.Content.ReadAsStringAsync().Result);
ultragridiew1.DataSource = data.s_name.namedatas;
}
Main change I have done is to use HttpClient. It removes a lot of boilerplate code that is required with webrequest.
#Chetan Ranpariya had correct me. Thank you
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public IList<Namedata> namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
string username = "myuser";
string password = "myuserpass";
byte[] byteArray = Encoding.UTF8.GetBytes("{\"name\":\"" + Name.Text + "\",\"id\":\"1\"}");
WebRequest request = WebRequest.Create("http://myservice/Service4.svc/s_name");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)));
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream = request.GetResponse().GetResponseStream();
var result = (new StreamReader(stream).ReadLine());
var exampleObj = JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = exampleObj.s_name.namedatas
}

How do i assign a value to a public const string variable?

I have this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web.Script.Serialization;
using System.Json;
using System.Runtime.Serialization.Json;
using System.Web.Helpers;
namespace Automatic_Record
{
class Youtube_Video_Information
{
public const string ytKey = "";
public int Width { get; set; }
public int Height { get; set; }
public int Duration { get; set; }
public string Title { get; set; }
public string ThumbUrl { get; set; }
public string BigThumbUrl { get; set; }
public string Description { get; set; }
public string VideoDuration { get; set; }
public string Url { get; set; }
public DateTime UploadDate { get; set; }
public bool YouTubeImport(string VideoID)
{
try
{
WebClient myDownloader = new WebClient();
myDownloader.Encoding = System.Text.Encoding.UTF8;
string jsonResponse = myDownloader.DownloadString("https://www.googleapis.com/youtube/v3/videos?id=" + VideoID + "&key=" + ytKey + "&part=snippet");
JavaScriptSerializer jss = new JavaScriptSerializer();
var dynamicObject = Json.Decode(jsonResponse);
var item = dynamicObject.items[0].snippet;
Title = item.title;
ThumbUrl = item.thumbnails.#default.url;
BigThumbUrl = item.thumbnails.high.url;
Description = item.description;
UploadDate = Convert.ToDateTime(item.publishedAt);
jsonResponse = myDownloader.DownloadString("https://www.googleapis.com/youtube/v3/videos?id=" + VideoID + "&key=" + ytKey + "&part=contentDetails");
dynamicObject = Json.Decode(jsonResponse);
string tmp = dynamicObject.items[0].contentDetails.duration;
Duration = Convert.ToInt32(System.Xml.XmlConvert.ToTimeSpan(tmp).TotalSeconds);
Url = "http://www.youtube.com/watch?v=" + VideoID;
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool VimeoImport(string VideoID)
{
try
{
WebClient myDownloader = new WebClient();
myDownloader.Encoding = System.Text.Encoding.UTF8;
string jsonResponse = myDownloader.DownloadString("http://vimeo.com/api/v2/video/" + VideoID + ".json");
JavaScriptSerializer jss = new JavaScriptSerializer();
var dynamicObject = Json.Decode(jsonResponse);
var item = dynamicObject[0];
Title = item.title;
Description = item.description;
Url = item.url;
ThumbUrl = item.thumbnail_small;
BigThumbUrl = item.thumbnail_large;
UploadDate = Convert.ToDateTime(item.upload_date);
Width = Convert.ToInt32(item.width);
Height = Convert.ToInt32(item.height);
Duration = Convert.ToInt32(item.duration);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
In form1 constructor i did:
Youtube_Video_Information.ytKey = "myapikey";
Youtube_Video_Information yvi = new Youtube_Video_Information();
yvi.YouTubeImport("ee-myvideoid");
The problem is that i'm getting error on:
Youtube_Video_Information.ytKey
Error 3 The left-hand side of an assignment must be a variable, property or indexer
How can i solve the error ?
How do i assign a value to a public const string variable?
You cannot. Const values cannot have a value assigned in runtime. If you need to be able to assign value in runtime, pass the value to a constructor call and make the member readonly.
class Youtube_Video_Information
{
public readonly string ytKey;
public Youtube_Video_Information(string ytKey)
{
this.ytKey = ytKey;
}
}

c# deserialize mutliple Json into same list

I have a Api link that returns this Json structure. In the code I request this Api link and then deserialize it into a list. This is done without problems. But if the Api returns more than 50 "counts" it creates another page. How do i get around to loop through all pages and add everything to the existing list?
In the case i linked there will be 38 pages. All need to be added to the list.
Call
// spidyApiUrl = http://www.gw2spidy.com/api/v0.9/json/item-search/iron/1
var spidyApi_idByName_result = api_Handler.objFromApi_idToName(spidyApiUrl);
Function with the return
public RootObject objFromApi_idToName(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
//return serializer.Deserialize<RootObject>(jsonReader);
RootObject rootObject = serializer.Deserialize<RootObject>(jsonReader);
if (rootObject.count > 0) { return rootObject; }
else { return null; }
}
}
And ofcourse i also have the get; set; classes.
How do I loop through all pages (if mutliple pages exist, which doesnt have to) and add these to the same object list.
You need continue downloading the data until page == last_page
As you get each page of data you then add the new set of results to the original rootObject's results property with AddRange
I also changed the url that gets passed into the function from
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/1
to
http://www.gw2spidy.com/api/v0.9/json/item-search/iron
This allows me to add the page numbers to the url to get all the pages
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/1
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/2
.....
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/38
Code:
public class Result
{
public int data_id { get; set; }
public string name { get; set; }
public int rarity { get; set; }
public int restriction_level { get; set; }
public string img { get; set; }
public int type_id { get; set; }
public int sub_type_id { get; set; }
public string price_last_changed { get; set; }
public int max_offer_unit_price { get; set; }
public int min_sale_unit_price { get; set; }
public int offer_availability { get; set; }
public int sale_availability { get; set; }
public int sale_price_change_last_hour { get; set; }
public int offer_price_change_last_hour { get; set; }
}
public class RootObject
{
public int count { get; set; }
public int page { get; set; }
public int last_page { get; set; }
public int total { get; set; }
public List<Result> results { get; set; }
}
class Program
{
static void Main(string[] args)
{
objFromApi_idToName("http://www.gw2spidy.com/api/v0.9/json/item-search/iron");
}
public static RootObject objFromApi_idToName(string url)
{
RootObject rootObject = null;
RootObject tempRootObject = null;
int page = 1;
do
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "/" + page);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
//return serializer.Deserialize<RootObject>(jsonReader);
tempRootObject = serializer.Deserialize<RootObject>(jsonReader);
if (rootObject == null)
{
rootObject = tempRootObject;
}
else
{
rootObject.results.AddRange(tempRootObject.results);
rootObject.count += tempRootObject.count;
}
}
page++;
} while (tempRootObject != null && tempRootObject.last_page != tempRootObject.page);
return rootObject;
}
}
Are you using Web API? If so, could you try something like this?
public RootObject objFromApi_idToName(string url)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("<your uri here>");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("<uri extention here>");
if (response.IsSuccessStatusCode)
{
string jsonStr = await response.Content.ReadAsStringAsync();
var deserializedResponse = JsonConvert.DeserializeObject<List<your model class here>>(jsonStr);
return deserializedResponse;
}
}

Web HttpRequest method in asp.net

My C# class
public class City
{
public int City_id { get; set; }
public string City_name { get; set; }
}
public class Model
{
public City[] lstCitiesResult { get; set; }
}
Web Request
string url = "my url";
WebRequest request = WebRequest.Create(url);
// provide your ID And Password for proxy
request.Proxy.Credentials = new NetworkCredential(XXXX);
WebResponse ws = request.GetResponse();
DataContractJsonSerializer jsonSerializer =
new DataContractJsonSerializer(typeof(List<Model>));
List<Model> dataList =
(List<Model>)jsonSerializer.ReadObject(ws.GetResponseStream());
string result = "";
foreach (var data1 in dataList)
{
result = result + data1.lstCitiesResult.ToString();
}
TextBox1.Text = result.ToString();
My error: I got null in datalist...what i do?

Paypal PDT with C#

I'm trying to implement a shopping cart tracking system using pdt with C#.
the trouble i have is finding an example of the paypal succes postback, especially in case of multiple items !
Any help woul be appreciated (some code will be much better :D)!
Thanks
The code below parses PDT response:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.Net;
using System.IO;
using System.Text;
namespace PayPal
{
public static class PaymentDataTransfer
{
private const string AppSetting_Identity = "PayPal.PaymentDataTransfer.Identity";
private const string AppSetting_ServiceUrl = "PayPal.PaymentDataTransfer.ServiceUrl";
public class TransactionStatus
{
public bool Success { get; set; }
public int ErrorCode { get; set; }
public NameValueCollection Parameters { get; set; }
public float PaymentGross { get; set; }
public string Currency { get; set; }
public string Invoice { get; set; }
public PayerInformation Payer { get; set; }
public CartItem[] CartItems;
}
public class PayerInformation
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
public class CartItem
{
public int Number { get; set; }
public string Name { get; set; }
public int Qunatity { get; set; }
public float GrossPrice { get; set; }
}
public static TransactionStatus GetTransactionStatus(string transactionToken)
{
return GetTransactionStatus(transactionToken, false);
}
public static TransactionStatus GetTransactionStatus(string transactionToken, bool sandbox)
{
#if ParsingTest
string response =
#"SUCCESS
mc_gross=1100.00
invoice=334354
protection_eligibility=Eligible
address_status=confirmed
item_number1=1
tax=0.00
item_number2=2
payer_id=DSFSDFSDFSDF
address_street=1+Main+St
payment_date=04%3A13%3A49+Oct+20%2C+2011+PDT
payment_status=Completed
charset=windows-1252
address_zip=95131
mc_shipping=0.00
mc_handling=0.00
first_name=Test
mc_fee=32.20
address_country_code=US
address_name=Test+User
custom=
payer_status=verified
business=yourbusiness%40business.com
address_country=United+States
num_cart_items=2
mc_handling1=0.00
mc_handling2=0.00
address_city=San+Jose
payer_email=payer_email%40business.com
mc_shipping1=0.00
mc_shipping2=0.00
txn_id=0SDFSDFSDFSDFD
payment_type=instant
last_name=User
address_state=CA
item_name1=First+test+item
receiver_email=yourbusiness%40business.com
item_name2=Second+test+item
payment_fee=32.20
quantity1=1
quantity2=1
receiver_id=SDFGDFGDFGDFDFG
txn_type=cart
mc_gross_1=1000.00
mc_currency=USD
mc_gross_2=100.00
residence_country=US
transaction_subject=Shopping+Cart
payment_gross=1100.00";
#else
string authToken = GetAppSetting(AppSetting_Identity, sandbox);
string serviceUrl = GetAppSetting(AppSetting_ServiceUrl, sandbox);
string query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionToken, authToken);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = query.Length;
using (var requestStreamWriter = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
requestStreamWriter.Write(query);
requestStreamWriter.Close();
}
string response;
// Do the request to PayPal and get the response
using(StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()))
{
response = stIn.ReadToEnd();
stIn.Close();
}
#endif
string[] lines = response.Split(new []{"\n", "\r\n"}, StringSplitOptions.None); // splitting up by line breaks
var result = new TransactionStatus
{
Success = lines[0] == "SUCCESS",
Parameters = new NameValueCollection()
};
for(int i=1; i < lines.Length; i++)
{
string line = lines[i];
string[] keyValuePair = lines[i].Split(new [] {'='});
if(keyValuePair.Length == 2)
{
result.Parameters.Add(UrlDecode(keyValuePair[0]), UrlDecode(keyValuePair[1]));
}
else
{
const string errorCodePrefix = "Error:";
if(line.StartsWith(errorCodePrefix))
{
result.ErrorCode = Int32.Parse(line.Substring(errorCodePrefix.Length));
}
}
}
if(result.Success)
{
result.Invoice = result.Parameters["invoice"];
result.Payer = new PayerInformation
{
FirstName = result.Parameters["first_name"],
LastName = result.Parameters["last_name"],
Email = result.Parameters["payer_email"]
};
float paymentGross;
result.PaymentGross = float.TryParse(result.Parameters["mc_gross"],
NumberStyles.Float,
CultureInfo.InvariantCulture,
out paymentGross) ? paymentGross : 0.0f;
result.Currency = result.Parameters["mc_currency"];
int cartItemsNumber;
if (int.TryParse(result.Parameters["num_cart_items"], out cartItemsNumber) && cartItemsNumber > 0)
{
var cartItems = new List<CartItem>();
for(int i=1; i <= cartItemsNumber; i++)
{
cartItems.Add(new CartItem
{
Number = int.Parse(result.Parameters["item_number" + i], CultureInfo.InvariantCulture),
Name = result.Parameters["item_name" + i],
Qunatity = int.Parse(result.Parameters["quantity" + i], CultureInfo.InvariantCulture),
GrossPrice = float.Parse(result.Parameters["mc_gross_" + i], CultureInfo.InvariantCulture)
});
}
result.CartItems = cartItems.ToArray();
}
}
return result;
}
private static string UrlDecode(string encodedText)
{
return Uri.UnescapeDataString(encodedText.Replace("+", " "));
}
private static string GetAppSetting(string settingName, bool sandbox)
{
return ConfigurationManager.AppSettings[settingName + (sandbox ? "_sandbox" : string.Empty)];
}
}
}
The configuration part from web.config:
<appSettings>
.....
<!-- PayPal -->
<add key="PayPal.PaymentDataTransfer.Identity" value="....." />
<add key="PayPal.PaymentDataTransfer.Identity_sandbox" value="....." />
<add key="PayPal.PaymentDataTransfer.ServiceUrl" value="https://www.paypal.com/cgi-bin/webscr" />
<add key="PayPal.PaymentDataTransfer.ServiceUrl_sandbox" value="https://www.sandbox.paypal.com/cgi-bin/webscr" />
</appSettings>
I believe this book has some good examples.
http://www.amazon.com/Beginning-ASP-NET-E-Commerce-2005-ebook/dp/B001JEPVVE/ref=sr_1_2?ie=UTF8&s=digital-text&qid=1268249356&sr=8-2

Categories

Resources