I've this error in my code:
Invalid object passed in, ':' or '}' expected. (14): { first_name =
teste, last_name = teste, dia = 1, mes = 1, ano = 1890, mail = 1890,
company = , ocupation = dsafad, pass = 123, country = Antigua, city =
ffff, user_type = 40 }
I'm trying to convert this string to json, but i can't how can i do this.
var user_data = new {
first_name = register.first_name,
last_name = register.last_name,
dia = register.dia,
mes = register.mes,
ano = register.ano,
mail = register.ano,
company = register.company,
ocupation = register.ocupation,
pass = register.pass,
country = register.country,
city = register.city,
user_type = register.user_type
};
Session["JSON_OBJECT-USER-PREMIUM"] = user_data;
and i do this on the other side to convert:
string new_user = Session["JSON_OBJECT-USER-PREMIUM"].ToString();
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, string>[]>(new_user);
Response.Write(data);
The object register itself will be enough for serialization.
Session["JSON_OBJECT-USER-PREMIUM"] = register;
// here the type Register is whatever the type of object 'register' is
Register new_user = (Register)Session["JSON_OBJECT-USER-PREMIUM"];
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(new_user);
Response.Write(json);
Deserialization:
var registerObject = serializer.Deserialize<Register>(json);
Response.Write(registerObject);
And with these little changes you can do it.
Related
Consider the following .proto definition:
syntax = "proto3";
option csharp_namespace = "Test";
message Book
{
string name = 1;
map<string, PersonInfo> persons = 2;
}
message PersonInfo
{
string name = 1;
string details = 2;
}
I want to serialize to a file an instance of Book and later deserialize it:
var book1 = new Book() { Name = "Book1" };
book1.Persons.Add("Person1", new PersonInfo() { Name = "Person1", Details = "Some details" });
//serialization
var book1JsonStr = JsonSerializer.Serialize(book1);
//unserialization
var book2 = JsonSerializer.Deserialize<Book>(book1JsonStr);
The object book1 is populated correctly:
And the serialized string is also correct:
The issue arises when we unserialize the object back:
"Regular" fields (string, double, int) are unserialized, but the map (Google.Protobuf.Collections.MapField<TKey, TValue>) it is not. Why this is happening? Is this a bug?
What can I do to unserialize a MapField?
Using Newtonsoft.Json instead of System.Text.Json solved this issue.
var book1 = new Book() { Name = "Book1" };
book1.Persons.Add("Person1", new PersonInfo() { Name = "Person1", Details = "Some details" });
//serialization
var book1JsonStr = JsonConvert.SerializeObject(book1);
//unserialization
var book2 = JsonConvert.SerializeObject<Book>(book1JsonStr);
You can use Protobuf.System.Text.Json extension for System.Text.Json to fix your issue.
var book1 = new Book() { Name = "Book1" };
book1.Persons.Add("Person1", new PersonInfo() { Name = "Person1", Details = "Some details" });
//serialization
var jsonSerializerOptions = new JsonSerializerOptions();
jsonSerializerOptions.AddProtobufSupport();
var book1JsonStr = JsonSerializer.Serialize(book1, jsonSerializerOptions);
//deserialization
var book2 = JsonSerializer.Deserialize<Book>(book1JsonStr, jsonSerializerOptions);
Trying to get address and its value to be curly brackets. means json object within a json object.
var jsonObject = new JObject();
dynamic j_obj = new JObject();
j_obj.jsonrpc = "1.0";
j_obj.id = "abc";
j_obj.method = "getrawtransaction";
j_obj.#params = new JArray() as dynamic;
dynamic info = new JObject();
info.txid = "myid";
info.vout = "0";
j_obj.#params.Add(info);
var address = "myaddress";
j_obj.Add(new JProperty(address, "0.01"));
Console.WriteLine(j_obj.ToString());
What I want is "address" and its value to be json object.
This is the output I am getting now.
Output Image
You are adding a value property here
var address = "myaddress";
j_obj.Add(new JProperty(address, "0.01"));
Instead create an object for the address then use that in the property:
dynamic addressItem = new JObject();
addressItem.line1 = "foo";
var address = "myaddress";
j_obj.Add(new JProperty(address, addressItem));
Alternatively, as you have gone down the dynamics route you could do this
j_obj.myaddress = new
{
line1 = "foo"
}
Either of these would create JSON that looks like this:
{
...
"myaddress": { "line1": "foo" }
...
}
I have a windows form application that has a slew of textboxes that I fill using a bunch of strings. My question is...the code works fine but it seems like a lot of wasteful typing. Can you fill the textboxes from the strings in a loop functions? Matching up the textbox with the approriate string?
Here is what I have.
var client = new WebClient { Credentials = new NetworkCredential(username, password) };
var financials = client.DownloadString("https://api.intrinio.com/data_point?identifier="+conver+"&item=beta,marketcap,52_week_high,52_week_low,adj_close_price,short_interest,analyst_target_price,next_earnings_date,percent_change,yr_percent_change,implied_volatility, dividendyield,listing_exchange,sector,average_daily_volume");
var jss = client.DownloadString("https://api.intrinio.com/companies?identifier=" + conver + "");
JObject rss = JObject.Parse(jss);
JObject fin = JObject.Parse(financials);
string RRSTITLE = (string)rss["legal_name"];
string beta = (string)fin.SelectToken("data[0].value");
string marketcap = (string)fin.SelectToken("data[1].value");
string weekhigh = (string)fin.SelectToken("data[2].value");
string weeklow = (string)fin.SelectToken("data[3].value");
string adj_close = (string)fin.SelectToken("data[4].value");
string short_interest = (string)fin.SelectToken("data[5].value");
string analyst_target = (string)fin.SelectToken("data[6].value");
string earnings = (string)fin.SelectToken("data[7].value");
string percent_change = (string)fin.SelectToken("data[8].value");
string yr_percent_change = (string)fin.SelectToken("data[9].value");
string implied = (string)fin.SelectToken("data[10].value");
string divyield = (string)fin.SelectToken("data[11].value");
string exchange = (string)fin.SelectToken("data[12].value");
string sector = (string)fin.SelectToken("data[13].value");
string volume = (string)fin.SelectToken("data[14].value");
company_textbox.Text = RRSTITLE;
beta_box.Text = beta;
marketCap_box.Text = marketcap;
wekhighbox.Text = weekhigh;
weklowbox.Text = weeklow;
adjclosebox.Text = adj_close;
shortbox.Text = short_interest;
targetestbox.Text = analyst_target;
next_earnings.Text = earnings;
Close_box.Text = percent_change;
percentytd.Text = yr_percent_change;
implivolbox.Text = implied;
divyieldbox.Text = divyield;
exchangebox.Text = exchange;
sectorbox.Text = sector;
daily_Volume_text.Text = volume;
Like #Jacky said, the straight forward answer is no. But a really hacky way would be to create two Dictionaries. Something like this
Dictionary<string, TextBox> TextBoxLookup = new Dictionary<string, TextBox>();
Dictionary<string, string> ValueLookup = new Dictionary<string, string>();
TextBoxLookup["beta"] = beta_box;
TextBoxLookup["marketcap"] = marketCap_box;
TextBoxLookup["weekhigh"] = wekhighbox;
ValueLookup["beta"] = beta;
ValueLookup["marketcap"] = marketcap;
ValueLookup["weekhigh"] = weekhigh;
foreach(string key in TextBoxLookup.Keys)
{
TextBoxLookup[key].Text = ValueLookup[key];
}
You'll have to add each textbook and its value to their respective dictionaries with the same key and iterate through the assignment foreach block everytime you need to assign.
Does this help?
I'm trying to work with the UPS api to create a shipping label. The UPS api uses a webservice to send an XML request to UPS. UPS then sends a response back. Here is my question.
Is there a way to view the XML that is outputted when I call the "shipmentRequest" method?
This is the first time I've used an API and a webservice so if you need me to provide more information just let me know.
Thanks!
EDIT: Here is my C# code
ShipService shpSvc = new ShipService();
ShipmentRequest shipmentRequest = new ShipmentRequest();
UPSSecurity upss = new UPSSecurity();
//shpSvc.Url = "https://onlinetools.ups.com/webservices/Ship";
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = apiCode;
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = userName;
upssUsrNameToken.Password = password;
upss.UsernameToken = upssUsrNameToken;
shpSvc.UPSSecurityValue = upss;
RequestType request = new RequestType();
String[] requestOption = { "nonvalidate" };
request.RequestOption = requestOption;
shipmentRequest.Request = request;
ShipmentType shipment = new ShipmentType();
shipment.Description = "Ship webservice example";
ShipperType shipper = new ShipperType();
shipper.ShipperNumber = accountNumber;
PaymentInfoType paymentInfo = new PaymentInfoType();
ShipmentChargeType shpmentCharge = new ShipmentChargeType();
BillShipperType billShipper = new BillShipperType();
billShipper.AccountNumber = accountNumber;
shpmentCharge.BillShipper = billShipper;
shpmentCharge.Type = "01";
ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
paymentInfo.ShipmentCharge = shpmentChargeArray;
shipment.PaymentInformation = paymentInfo;
ShipWSSample.ShipWebReference.ShipAddressType shipperAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] addressLine = { "480 Parkton Plaza" };
shipperAddress.AddressLine = addressLine;
shipperAddress.City = "Timonium";
shipperAddress.PostalCode = "21093";
shipperAddress.StateProvinceCode = "MD";
shipperAddress.CountryCode = "US";
shipperAddress.AddressLine = addressLine;
shipper.Address = shipperAddress;
shipper.Name = "ABC Associates";
shipper.AttentionName = "ABC Associates";
ShipPhoneType shipperPhone = new ShipPhoneType();
shipperPhone.Number = "1234567890";
shipper.Phone = shipperPhone;
shipment.Shipper = shipper;
ShipFromType shipFrom = new ShipFromType();
ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] shipFromAddressLine = { "Ship From Street" };
shipFromAddress.AddressLine = addressLine;
shipFromAddress.City = "Timonium";
shipFromAddress.PostalCode = "21093";
shipFromAddress.StateProvinceCode = "MD";
shipFromAddress.CountryCode = "US";
shipFrom.Address = shipFromAddress;
shipFrom.AttentionName = "Mr.ABC";
shipFrom.Name = "ABC Associates";
shipment.ShipFrom = shipFrom;
ShipToType shipTo = new ShipToType();
ShipToAddressType shipToAddress = new ShipToAddressType();
String[] addressLine1 = { "Some Street" };
shipToAddress.AddressLine = addressLine1;
shipToAddress.City = "Roswell";
shipToAddress.PostalCode = "30076";
shipToAddress.StateProvinceCode = "GA";
shipToAddress.CountryCode = "US";
shipTo.Address = shipToAddress;
shipTo.AttentionName = "DEF";
shipTo.Name = "DEF Associates";
ShipPhoneType shipToPhone = new ShipPhoneType();
shipToPhone.Number = "1234567890";
shipTo.Phone = shipToPhone;
shipment.ShipTo = shipTo;
ServiceType service = new ServiceType();
service.Code = "01";
shipment.Service = service;
PackageType package = new PackageType();
PackageWeightType packageWeight = new PackageWeightType();
packageWeight.Weight = "1";
ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
uom.Code = "LBS";
packageWeight.UnitOfMeasurement = uom;
package.PackageWeight = packageWeight;
PackagingType packType = new PackagingType();
packType.Code = "02";
package.Packaging = packType;
PackageType[] pkgArray = { package };
shipment.Package = pkgArray;
LabelSpecificationType labelSpec = new LabelSpecificationType();
LabelStockSizeType labelStockSize = new LabelStockSizeType();
labelStockSize.Height = "6";
labelStockSize.Width = "4";
labelSpec.LabelStockSize = labelStockSize;
LabelImageFormatType labelImageFormat = new LabelImageFormatType();
labelImageFormat.Code = "SPL";
labelSpec.LabelImageFormat = labelImageFormat;
shipmentRequest.LabelSpecification = labelSpec;
shipmentRequest.Shipment = shipment;
ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
MessageBox.Show("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
MessageBox.Show("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
You can inherit from the UPS service and read the response as xml by providing your own XmlWriter by overriding GetWriterForMessage(). You can see a working example here.
i am using this code display xml it may help you.
XDocument mySourceDoc = new XDocument();
mySourceDoc = XDocument.Load(shipmentResponse);
txtxml.Text = mySourceDoc.ToString();
I am working on Expedia hotel API.All the function are working except booking.All the other request using GET method for requesting.But in booking we have to use the POST method with different URL.So i changed the URL for request but still getting the error.
My codes are
HotelServicesImplService client = new HotelServicesImplService();
HotelRoomReservationRequest bookreq = new HotelRoomReservationRequest();
HotelRoomReservationResponse bookres = new HotelRoomReservationResponse();
addressInfo bookad = new addressInfo();
reservationInfo bookinfo = new reservationInfo();
client.Url = "https://book.api.ean.com/ean-services/rs/hotel/v3";
//bookreq.minorRevSpecified = true;
//bookreq.minorRev = 25;
bookreq.hotelId = 106347;
bookreq.apiKey = "api";
bookreq.cid = "cid";
bookreq.arrivalDate = "12/11/2013";
bookreq.departureDate = "12/13/2013";
bookreq.supplierType = SupplierType.E;
bookreq.rateKey = "af00b688-acf4-409e-8bdc-fcfc3d1cb80c";
bookreq.roomTypeCode = "198058";
bookreq.rateCode = "484072";
bookreq.RoomGroup = new[] { new Room
{
numberOfAdults=Convert.ToInt32(2),
numberOfChildren=Convert.ToInt32(0),
childAges=new int[] {} ,
firstName="Test Booking",
lastName="Test Booking",
bedTypeId="23",
smokingPreference=SmokingPreference.NS,
}};
float i = float.Parse("231.18");
bookreq.currencyCode = "USD";
bookreq.chargeableRate = i;
bookinfo.email = "ranaabhi007#yahoo.com";
bookinfo.firstName = "TestBooking";
bookinfo.lastName = "TestBooking";
bookinfo.homePhone = "2145370159";
bookinfo.workPhone = "2145370159";
bookinfo.creditCardType = "CA";
bookinfo.creditCardNumber = "5401999999999999";
bookinfo.creditCardIdentifier = "TestBooking";
bookinfo.creditCardExpirationMonth = "12";
bookinfo.creditCardExpirationYear = "2015";
bookad.city = "Seattle";
bookad.stateProvinceCode = "WA";
bookad.countryCode = "US";
bookad.postalCode = "98004";
bookreq.ReservationInfo = bookinfo;
bookad.address1 = "travelnow";
//bookad.city = txtCity.Text;
//bookad.stateProvinceCode = txtState.Text;
//bookad.countryCode = txtCountry.Text;
//bookad.postalCode = txtPostal.Text;
bookreq.AddressInfo = bookad;
bookres = client.getReservation(bookreq);
// HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(client);
Response.Write(bookres.confirmationNumbers);
Response.Write(bookres.departureDate);
Response.Write(bookres.drivingDirections);
Response.Write(bookres.CouponInformationResponse);
but i am still getting the error
The request failed with HTTP status 404: Not Found.
Are you sure your URL is correct? According to the documentation, it should be
https://book.api.ean.com/ean-services/rs/hotel/v3/res