type=CREATE
resource=transaction
number_of_attempts=1
data={"id":"11e7df5131dd9820bf774044","payment_method":"cc","account_vault_id":null,"recurring_id":null,"first_six":"411111","last_four":"1111","account_holder_name":" MALCOLM BLACK","transaction_amount":"1.00","description":null,"transaction_code":null,"avs":null,"batch":"2","order_num":"798279608211","verbiage":"APPROVAL","transaction_settlement_status":null,"effective_date":null,"routing":null,"return_date":null,"created_ts":1513092547,"modified_ts":1513092547,"transaction_api_id":null,"terms_agree":null,"notification_email_address":null,"notification_email_sent":true,"response_message":null,"auth_amount":"1.00","auth_code":"df5132","status_id":101,"type_id":20,"location_id":"11e7c499daaff1f0a7507909","reason_code_id":1000,"contact_id":"11e7c619b69d209ab41b24dc","billing_zip":"","billing_street":null,"product_transaction_id":"11e7c499db893b0489bb3739","tax":"0.000","customer_ip":null,"customer_id":null,"po_number":null,"avs_enhanced":"V","cvv_response":"N","billing_phone":null,"billing_city":null,"billing_state":null,"clerk_number":null,"tip_amount":"0.00","created_user_id":"11e7c499dac79026a4e740f1","modified_user_id":"11e7c499dac79026a4e740f1","settle_date":null,"charge_back_date":null,"void_date":null,"account_type":"visa","is_recurring":false,"is_accountvault":false,"transaction_c1":null,"transaction_c2":null,"transaction_c3":null,"additional_amounts":[],"terminal_serial_number":null,"entry_mode_id":"K","terminal_id":null,"quick_invoice_id":null,"emv_receipt_data":null}
This is the Form data i am receiving in C# using
string data=Request.Form("data");
Now data is nested how can i get the values of data object. Parsing it in json using JsonConvert.Deserialize is throwing exception.
The original response is:
type=CREATE&resource=transaction&number_of_attempts=1&data=%7b%22id%22%3a%2211e7df5131dd9820bf774044%22%2c%22payment_method%22%3a%22cc%22%2c%22account_vault_id%22%3anull%2c%22recurring_id%22%3anull%2c%22first_six%22%3a%22411111%22%2c%22last_four%22%3a%221111%22%2c%22account_holder_name%22%3a%22+MALCOLM+BLACK%22%2c%22transaction_amount%22%3a%221.00%22%2c%22description%22%3anull%2c%22transaction_code%22%3anull%2c%22avs%22%3anull%2c%22batch%22%3a%222%22%2c%22order_num%22%3a%22798279608211%22%2c%22verbiage%22%3a%22APPROVAL%22%2c%22transaction_settlement_status%22%3anull%2c%22effective_date%22%3anull%2c%22routing%22%3anull%2c%22return_date%22%3anull%2c%22created_ts%22%3a1513092547%2c%22modified_ts%22%3a1513092547%2c%22transaction_api_id%22%3anull%2c%22terms_agree%22%3anull%2c%22notification_email_address%22%3anull%2c%22notification_email_sent%22%3atrue%2c%22response_message%22%3anull%2c%22auth_amount%22%3a%221.00%22%2c%22auth_code%22%3a%22df5132%22%2c%22status_id%22%3a101%2c%22type_id%22%3a20%2c%22location_id%22%3a%2211e7c499daaff1f0a7507909%22%2c%22reason_code_id%22%3a1000%2c%22contact_id%22%3a%2211e7c619b69d209ab41b24dc%22%2c%22billing_zip%22%3a%22%22%2c%22billing_street%22%3anull%2c%22product_transaction_id%22%3a%2211e7c499db893b0489bb3739%22%2c%22tax%22%3a%220.000%22%2c%22customer_ip%22%3anull%2c%22customer_id%22%3anull%2c%22po_number%22%3anull%2c%22avs_enhanced%22%3a%22V%22%2c%22cvv_response%22%3a%22N%22%2c%22billing_phone%22%3anull%2c%22billing_city%22%3anull%2c%22billing_state%22%3anull%2c%22clerk_number%22%3anull%2c%22tip_amount%22%3a%220.00%22%2c%22created_user_id%22%3a%2211e7c499dac79026a4e740f1%22%2c%22modified_user_id%22%3a%2211e7c499dac79026a4e740f1%22%2c%22settle_date%22%3anull%2c%22charge_back_date%22%3anull%2c%22void_date%22%3anull%2c%22account_type%22%3a%22visa%22%2c%22is_recurring%22%3afalse%2c%22is_accountvault%22%3afalse%2c%22transaction_c1%22%3anull%2c%22transaction_c2%22%3anull%2c%22transaction_c3%22%3anull%2c%22additional_amounts%22%3a%5b%5d%2c%22terminal_serial_number%22%3anull%2c%22entry_mode_id%22%3a%22K%22%2c%22terminal_id%22%3anull%2c%22quick_invoice_id%22%3anull%2c%22emv_receipt_data%22%3anull%7d
UPDATE:
try
{
string data = #Request.Form.Get("data");
//now data=
//{"id":"11e7df5131dd9820bf774044","payment_method":"cc","account_vault_id":n//ull.....}
//data = '"' + data + '"';
var stringfy = JsonConvert.DeserializeObject(data);
File.WriteAllText(path, " File Data : " + Request.Form +
Environment.NewLine + " --------------------Total Value 0 " + Request.Form.Keys[0].ToString()
+ Environment.NewLine + " --------------------Total Value 1 " + Request.Form.Keys[1].ToString()
+ Environment.NewLine + " --------------------Total Value 2 " + Request.Form.Keys[2].ToString()
+ Environment.NewLine + " --------------------Total Value 3 " + data);
}
catch (Exception ex)
{
File.WriteAllText(path, "Exception :1 "+ex.Message.ToString());
}
Code is deployed on server so writing exceptions to file but, no code after Deserialize statement is working and no file is being created.
There is a shortcut. You can use this website as a helper - http://json2csharp.com/
All you need to do is past this string {"id":"11e7d...} then click generate.
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var data = Welcome.FromJson(jsonString);
//
namespace QuickType
{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
public partial class Welcome
{
[JsonProperty("account_holder_name")]
public string AccountHolderName { get; set; }
[JsonProperty("account_type")]
public string AccountType { get; set; }
[JsonProperty("account_vault_id")]
public object AccountVaultId { get; set; }
[JsonProperty("additional_amounts")]
public object[] AdditionalAmounts { get; set; }
[JsonProperty("auth_amount")]
public string AuthAmount { get; set; }
[JsonProperty("auth_code")]
public string AuthCode { get; set; }
[JsonProperty("avs")]
public object Avs { get; set; }
[JsonProperty("avs_enhanced")]
public string AvsEnhanced { get; set; }
[JsonProperty("batch")]
public string Batch { get; set; }
[JsonProperty("billing_city")]
public object BillingCity { get; set; }
[JsonProperty("billing_phone")]
public object BillingPhone { get; set; }
[JsonProperty("billing_state")]
public object BillingState { get; set; }
[JsonProperty("billing_street")]
public object BillingStreet { get; set; }
[JsonProperty("billing_zip")]
public string BillingZip { get; set; }
[JsonProperty("charge_back_date")]
public object ChargeBackDate { get; set; }
[JsonProperty("clerk_number")]
public object ClerkNumber { get; set; }
[JsonProperty("contact_id")]
public string ContactId { get; set; }
[JsonProperty("created_ts")]
public long CreatedTs { get; set; }
[JsonProperty("created_user_id")]
public string CreatedUserId { get; set; }
[JsonProperty("customer_id")]
public object CustomerId { get; set; }
[JsonProperty("customer_ip")]
public object CustomerIp { get; set; }
[JsonProperty("cvv_response")]
public string CvvResponse { get; set; }
[JsonProperty("description")]
public object Description { get; set; }
[JsonProperty("effective_date")]
public object EffectiveDate { get; set; }
[JsonProperty("emv_receipt_data")]
public object EmvReceiptData { get; set; }
[JsonProperty("entry_mode_id")]
public string EntryModeId { get; set; }
[JsonProperty("first_six")]
public string FirstSix { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("is_accountvault")]
public bool IsAccountvault { get; set; }
[JsonProperty("is_recurring")]
public bool IsRecurring { get; set; }
[JsonProperty("last_four")]
public string LastFour { get; set; }
[JsonProperty("location_id")]
public string LocationId { get; set; }
[JsonProperty("modified_ts")]
public long ModifiedTs { get; set; }
[JsonProperty("modified_user_id")]
public string ModifiedUserId { get; set; }
[JsonProperty("notification_email_address")]
public object NotificationEmailAddress { get; set; }
[JsonProperty("notification_email_sent")]
public bool NotificationEmailSent { get; set; }
[JsonProperty("order_num")]
public string OrderNum { get; set; }
[JsonProperty("payment_method")]
public string PaymentMethod { get; set; }
[JsonProperty("po_number")]
public object PoNumber { get; set; }
[JsonProperty("product_transaction_id")]
public string ProductTransactionId { get; set; }
[JsonProperty("quick_invoice_id")]
public object QuickInvoiceId { get; set; }
[JsonProperty("reason_code_id")]
public long ReasonCodeId { get; set; }
[JsonProperty("recurring_id")]
public object RecurringId { get; set; }
[JsonProperty("response_message")]
public object ResponseMessage { get; set; }
[JsonProperty("return_date")]
public object ReturnDate { get; set; }
[JsonProperty("routing")]
public object Routing { get; set; }
[JsonProperty("settle_date")]
public object SettleDate { get; set; }
[JsonProperty("status_id")]
public long StatusId { get; set; }
[JsonProperty("tax")]
public string Tax { get; set; }
[JsonProperty("terminal_id")]
public object TerminalId { get; set; }
[JsonProperty("terminal_serial_number")]
public object TerminalSerialNumber { get; set; }
[JsonProperty("terms_agree")]
public object TermsAgree { get; set; }
[JsonProperty("tip_amount")]
public string TipAmount { get; set; }
[JsonProperty("transaction_amount")]
public string TransactionAmount { get; set; }
[JsonProperty("transaction_api_id")]
public object TransactionApiId { get; set; }
[JsonProperty("transaction_c1")]
public object TransactionC1 { get; set; }
[JsonProperty("transaction_c2")]
public object TransactionC2 { get; set; }
[JsonProperty("transaction_c3")]
public object TransactionC3 { get; set; }
[JsonProperty("transaction_code")]
public object TransactionCode { get; set; }
[JsonProperty("transaction_settlement_status")]
public object TransactionSettlementStatus { get; set; }
[JsonProperty("type_id")]
public long TypeId { get; set; }
[JsonProperty("verbiage")]
public string Verbiage { get; set; }
[JsonProperty("void_date")]
public object VoidDate { get; set; }
}
public partial class Welcome
{
public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, Converter.Settings);
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
}
Related
I faced the problem: Cannot deserialize the current JSON object.
As follows:
public List<Track> Tracks { get; set; }
public async Task<List<Track>> GetTracking()
{
using (var httpClient = new HttpClient())
{
using (var requests = new HttpRequestMessage(new HttpMethod("GET"), "urlxxxxxxxx..."))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
requests.Headers.TryAddWithoutValidation("accept", "application/json");
var response = await httpClient.SendAsync(requests);
using (HttpContent content = response.Content)
{
var jsonStr = content.ReadAsStringAsync().GetAwaiter().GetResult();
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr); //Get Error**
Tracks = res;
}
}
}
return Tracks;
}
Model Class
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferences> documentReferences { get; set; }
public TransportCall transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public LocationMearsk location { get; set; }
public VesselMearsk vessel { get; set; }
}
My input data:
https://drive.google.com/file/d/12g0nHkHlmbU4Af8crHlzKXD_ERIZdCyH/view?usp=sharing
As in my description. I get the error: I get the error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[XX. Models.Track]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Even though I declared: public List events { get; set; }
Is the problem I have misunderstood the format of DeserializeObject. Looking forward to everyone's help. Thank
you have an object, not an array
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
and fix class
public class Events
{
....
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
Your model is incomplete and has typos. Assuming you have the correct versions of them.
You are doing:
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr);
which should be just:
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
Your json doesn't have an array at the root level.
Full working sample:
void Main()
{
var res = JsonConvert.DeserializeObject<Track>(myJson);
}
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public Location location { get; set; }
public Vessel vessel { get; set; }
}
public partial class Location
{
public string LocationName { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string UnLocationCode { get; set; }
public string FacilityCode { get; set; }
public string FacilityCodeListProvider { get; set; }
}
public partial class Vessel
{
public long VesselImoNumber { get; set; }
public string VesselName { get; set; }
public string VesselFlag { get; set; }
public string VesselCallSignNumber { get; set; }
public string VesselOperatorCarrierCode { get; set; }
public string VesselOperatorCarrierCodeListProvider { get; set; }
}
static readonly string myJson = #"{
""events"": [
{
""eventID"": ""6832920321"",
""eventType"": ""SHIPMENT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""shipmentEventTypeCode"": ""DRFT"",
""documentTypeCode"": ""SHI"",
""documentID"": ""205284917""
},
{
""eventID"": ""6832920321"",
""eventType"": ""TRANSPORT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""transportEventTypeCode"": ""ARRI"",
""documentReferences"": [
{
""documentReferenceType"": ""BKG"",
""documentReferenceValue"": ""ABC123123123""
},
{
""documentReferenceType"": ""TRD"",
""documentReferenceValue"": ""85943567-eedb-98d3-f4ed-aed697474ed4""
}
],
""transportCall"": {
""transportCallID"": ""123e4567-e89b-12d3-a456-426614174000"",
""carrierServiceCode"": ""FE1"",
""exportVoyageNumber"": ""2103S"",
""importVoyageNumber"": ""2103N"",
""transportCallSequenceNumber"": 2,
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG"",
""facilityTypeCode"": ""POTE"",
""otherFacility"": ""Balboa Port Terminal, Avenida Balboa Panama"",
""modeOfTransport"": ""VESSEL"",
""location"": {
""locationName"": ""Eiffel Tower"",
""latitude"": ""48.8585500"",
""longitude"": ""2.294492036"",
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG""
},
""vessel"": {
""vesselIMONumber"": 1801323,
""vesselName"": ""King of the Seas"",
""vesselFlag"": ""DE"",
""vesselCallSignNumber"": ""NCVV"",
""vesselOperatorCarrierCode"": ""MAEU"",
""vesselOperatorCarrierCodeListProvider"": ""NMFTA""
}
}
}
]
}";
EDIT: Result is something like:
I have created an API that I am now attempting to access through another application. Even though I am using Newtonsoft.JSON to both serialize and deserialize the JSON, I am encountering a conversion error, with the following InnerException:
{"Could not cast or convert from System.String to System.Collections.Generic.List`1[MidamAPI.Models.ManagerDTO]."}
The following is the snippet that throws the error (in RESTFactory):
public List<T> Execute<T>(String endPoint) where T : new() {
RestClient client = new RestClient(BASE_URL);
IRestRequest req = new RestRequest(endPoint);
req.AddHeader("Authorization", "Bearer " + this._token);
var response = client.Execute(req).Content;
List<T> responseData = JsonConvert.DeserializeObject<List<T>>(response);
return responseData;
}
which is called here:
{
RegisterViewModel vm = new RegisterViewModel();
RESTFactory factory = new RESTFactory((String)Session["bearer"]);
vm.availableManager = factory.Execute<ManagerDTO>("managers");
vm.availableProperties = factory.Execute<PropertyDTO>("locations");
vm.availableTrainers = factory.Execute<TrainerDTO>("trainers");
return View(vm);
}
The information is coming from the following API controller action (in a separate application):
[LocalFilter]
[RoutePrefix("managers")]
public class ManagersController : ApiController
{
UnitOfWork worker = new UnitOfWork();
[Route("")]
public string Get()
{
IEnumerable<ManagerDTO> dtoList = Mapper.Map<List<Manager>, List<ManagerDTO>>(worker.ManagerRepo.Get().ToList());
foreach (ManagerDTO dto in dtoList)
{
Manager manager = worker.ManagerRepo.GetByID(dto.ID);
dto.Stores = (Mapper.Map<IEnumerable<Property>, IEnumerable<PropertyDTO>>(manager.Properties)).ToList();
}
return JsonConvert.SerializeObject(dtoList);
}
The DTOs are the same in both applications:
{
public class ManagerDTO
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<PropertyDTO> Stores { get; set; }
}
public class PropertyDTO
{
public int ID;
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public string TrainerEmail { get; set; }
}
I tried using the json2csharp tool with the response, and everything seems fine to my eyes:
public class Store
{
public int ID { get; set; }
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public object TrainerEmail { get; set; }
}
public class RootObject
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<Store> Stores { get; set; }
}
Any advice would be appreciated.
EDIT:
The RegisterViewModel class
public class RegisterViewModel
{
public RegistrationDTO regModel { get; set; }
public List<ManagerDTO> availableManager { get; set; }
public List<PropertyDTO> availableProperties { get; set; }
public List<TrainerDTO> availableTrainers { get; set; }
}
Make your controller Get() return type
IHttpActionResult
and return
Ok(dtoList);
I am trying to deserialize my json code. The json code is in a string, and the json code looks like this (so I'm assuming it's json objects)
{
"post_id":13,
"thread_id":9,
"user_id":1,
"username":"Username",
"post_date":1496439611,
"message":"testzilla - 2133746943A9",
"ip_id":698,
"message_state":"visible",
"attach_count":0,
"position":0,
"likes":0,
"like_users":"a:0:{}",
"warning_id":0,
"warning_message":"",
"last_edit_date":1496476199,
"last_edit_user_id":0,
"edit_count":9,
"node_id":34,
"title":"Test",
"tags":"a:0:{}",
"node_title":"test node",
"node_name":null,
"message_html":"testzilla - 2133746943A9",
"absolute_url":"url"
}
How would I put the "message" container inside a string? So that the string would contain "testzilla - 2133746943A9" without the quotation marks. I am using JSON.Net
The name of the string that contains this json code is "MACs". Thanks in advance. PS: I am a new coder.
there is a missing "{" at the beginning of your json file, try adding it
You need to create your c# class to deserialize your json string. As per your json structure i have created your class given below
public class MyClass
{
public int post_id { get; set; }
public int thread_id { get; set; }
public int user_id { get; set; }
public string username { get; set; }
public int post_date { get; set; }
public string message { get; set; }
public int ip_id { get; set; }
public string message_state { get; set; }
public int attach_count { get; set; }
public int position { get; set; }
public int likes { get; set; }
public string like_users { get; set; }
public int warning_id { get; set; }
public string warning_message { get; set; }
public int last_edit_date { get; set; }
public int last_edit_user_id { get; set; }
public int edit_count { get; set; }
public int node_id { get; set; }
public string title { get; set; }
public string tags { get; set; }
public string node_title { get; set; }
public object node_name { get; set; }
public string message_html { get; set; }
public string absolute_url { get; set; }
}
No need to use library JSON.Net. You can do this by simply using System.Web.Script.Serialization to deserialize the json string.
Note : System.Web.Script.Serialization is available inside System.Web.Extensions namespace.
Below is the complete code. I kept your json data inside a file named as "test2.json" and consuming it from that file.
using System;
using System.Web.Script.Serialization;
using System.IO;
namespace DesrializeJson1ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var jsonFile = "test2.json";
string jsonstring = File.ReadAllText(jsonFile);
var serializer = new JavaScriptSerializer();
MyClass aClass = serializer.Deserialize<MyClass>(jsonstring);
Console.WriteLine("--------------------------");
Console.WriteLine("message :" + aClass.message);
Console.WriteLine("message_state :" + aClass.message_state);
Console.WriteLine("warning_message :" + aClass.warning_message);
Console.WriteLine("message_html :" + aClass.message_html);
Console.WriteLine("--------------------------");
Console.Read();
}
}
public class MyClass
{
public int post_id { get; set; }
public int thread_id { get; set; }
public int user_id { get; set; }
public string username { get; set; }
public int post_date { get; set; }
public string message { get; set; }
public int ip_id { get; set; }
public string message_state { get; set; }
public int attach_count { get; set; }
public int position { get; set; }
public int likes { get; set; }
public string like_users { get; set; }
public int warning_id { get; set; }
public string warning_message { get; set; }
public int last_edit_date { get; set; }
public int last_edit_user_id { get; set; }
public int edit_count { get; set; }
public int node_id { get; set; }
public string title { get; set; }
public string tags { get; set; }
public string node_title { get; set; }
public object node_name { get; set; }
public string message_html { get; set; }
public string absolute_url { get; set; }
}
}
OUTPUT
You can use regex to get the value you want.
string yourJsonString = #"{ ""post_id"":13, ""thread_id"":9, ""user_id"":1, ""username"":""Username"", ""post_date"":1496439611, ""message"":""testzilla - 2133746943A9"", ""ip_id"":698, ""message_state"":""visible"", ""attach_count"":0, ""position"":0, ""likes"":0, ""like_users"":""a:0:{}"", ""warning_id"":0, ""warning_message"":"""", ""last_edit_date"":1496476199, ""last_edit_user_id"":0, ""edit_count"":9, ""node_id"":34, ""title"":""Test"", ""tags"":""a:0:{}"", ""node_title"":""test node"", ""node_name"":null, ""message_html"":""testzilla - 2133746943A9"", ""absolute_url"":""url""}";
string value = System.Text.RegularExpressions.Regex.Match(yourJsonString,#"""message"":(.+?),").Groups[1].Value.Replace(#"""","");
MessageBox.Show(value);
You can also use dynamic type for deserialization. You will no need to write object for deserialization:
var str = "{\r\n \"post_id\":13,\r\n \"thread_id\":9,\r\n \"user_id\":1,\r\n \"username\":\"Username\",\r\n \"post_date\":1496439611,\r\n \"message\":\"testzilla - 2133746943A9\",\r\n \"ip_id\":698,\r\n \"message_state\":\"visible\",\r\n \"attach_count\":0,\r\n \"position\":0,\r\n \"likes\":0,\r\n \"like_users\":\"a:0:{}\",\r\n \"warning_id\":0,\r\n \"warning_message\":\"\",\r\n \"last_edit_date\":1496476199,\r\n \"last_edit_user_id\":0,\r\n \"edit_count\":9,\r\n \"node_id\":34,\r\n \"title\":\"Test\",\r\n \"tags\":\"a:0:{}\",\r\n \"node_title\":\"test node\",\r\n \"node_name\":null,\r\n \"message_html\":\"testzilla - 2133746943A9\",\r\n \"absolute_url\":\"url\"\r\n}";
dynamic obj = JsonConvert.DeserializeObject(str);
var postId = obj.post_id;
Console.WriteLine("postId:" + postId);
output:
postId:13
I have this json
and i want to deserialize it so I can get each object's value for example:
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpouLWzKjhzw8zFdC5K092kl5SClMj3PLXFhGpC_Pp8j-3I4IG7i1Hn_UI-Nmj3ItDGe1BoN1mCr1G4xL_vhMS8tcmcn3JhuihwsHvbzQv3309k3tBw8A",
The problem is I can make the class(es) that I need so I can deserialize the json because the json string has nested objects.
I used json2csharp to help me generate classes. After some merging and cleaning up, this is what I got:
public class InventoryItem
{
public string id { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string amount { get; set; }
public int pos { get; set; }
}
public class AppData
{
public string def_index { get; set; }
public int? is_itemset_name { get; set; }
public int? limited { get; set; }
}
public class Description
{
public string type { get; set; }
public string value { get; set; }
public string color { get; set; }
public AppData app_data { get; set; }
}
public class Action
{
public string name { get; set; }
public string link { get; set; }
}
public class Tag
{
public string internal_name { get; set; }
public string name { get; set; }
public string category { get; set; }
public string category_name { get; set; }
public string color { get; set; }
}
public class RgDescription
{
public string appid { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string icon_url { get; set; }
public string icon_url_large { get; set; }
public string icon_drag_url { get; set; }
public string name { get; set; }
public string market_hash_name { get; set; }
public string market_name { get; set; }
public string name_color { get; set; }
public string background_color { get; set; }
public string type { get; set; }
public int tradable { get; set; }
public int marketable { get; set; }
public int commodity { get; set; }
public string market_tradable_restriction { get; set; }
public List<Description> descriptions { get; set; }
public List<Action> actions { get; set; }
public List<Action> market_actions { get; set; }
public List<Tag> tags { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public IDictionary<string, InventoryItem> rgInventory { get; set; }
public List<object> rgCurrency { get; set; }
public IDictionary<string, RgDescription> rgDescriptions { get; set; }
public bool more { get; set; }
public bool more_start { get; set; }
}
These appear to work correctly, you can deserialize and serialize with code like this:
var obj = JsonConvert.DeserializeObject<RootObject>(oldString);
Console.WriteLine(obj.rgDescriptions["310776560_302028390"].icon_url); // e.g.
var newString = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// null value handling is optional, the above makes it a little more like the source string
So I have been able to get JSON objects for a few things, however this object is quite a bit more complex.
I'm trying to get comments from Reddit.
Here is the method I use:
public async Task<List<string>> GetComments(string currentSubreddit, string topicID)
{
string commentUrl = "http://www.reddit.com/r/" + currentSubreddit + "/comments/" + topicID + "/.json";
List<Comments> commentList = new List<Comments>();
string jsonText = await wc.GetJsonText(commentUrl);
Comments.RootObject deserializeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Comments.RootObject>(jsonText);
List<string> commentListTest = new List<string>();
//List<string> commentListTest = deserializeObject.data.children[0].data.children;
return commentListTest;
}
This is the GetJsonText method:
public async Task<string> GetJsonText(string url)
{
var request = WebRequest.Create(url);
string text;
request.ContentType = "application/json; charset=utf-8";
var response = (HttpWebResponse)await request.GetResponseAsync();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return text;
}
And here is a link to the Object: http://pastebin.com/WQ8XXGNA
And a link to the jsonText: http://pastebin.com/7Kh6cA9a
The error returned says this:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in mscorlib.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'JuicyReddit.Comments+RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I'd appreciate if anybody could help me with figuring out whats wrong with this.
Thanks
There are a few problems with your code actually
public async Task<List<string>> GetComments(string currentSubreddit, string topicID)
You don't need to return a list of string here, u need to return a full object
First rename RootObject in the model to an appropriate name such as "CommentsObject"
So set up your class like so and name it CommentsObject.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YOURNAMESPACE.Comments
{
public class MediaEmbed
{
}
public class SecureMediaEmbed
{
}
public class Data4
{
public int count { get; set; }
public string parent_id { get; set; }
public List<string> children { get; set; }
public string name { get; set; }
public string id { get; set; }
public string subreddit_id { get; set; }
public object banned_by { get; set; }
public string subreddit { get; set; }
public object likes { get; set; }
public object replies { get; set; }
public bool? saved { get; set; }
public int? gilded { get; set; }
public string author { get; set; }
public object approved_by { get; set; }
public string body { get; set; }
public object edited { get; set; }
public object author_flair_css_class { get; set; }
public int? downs { get; set; }
public string body_html { get; set; }
public string link_id { get; set; }
public bool? score_hidden { get; set; }
public double? created { get; set; }
public object author_flair_text { get; set; }
public double? created_utc { get; set; }
public object distinguished { get; set; }
public object num_reports { get; set; }
public int? ups { get; set; }
}
public class Child2
{
public string kind { get; set; }
public Data4 data { get; set; }
}
public class Data3
{
public string modhash { get; set; }
public List<Child2> children { get; set; }
public object after { get; set; }
public object before { get; set; }
}
public class Replies
{
public string kind { get; set; }
public Data3 data { get; set; }
}
public class Data2
{
public string domain { get; set; }
public object banned_by { get; set; }
public MediaEmbed media_embed { get; set; }
public string subreddit { get; set; }
public object selftext_html { get; set; }
public string selftext { get; set; }
public object likes { get; set; }
public object secure_media { get; set; }
public object link_flair_text { get; set; }
public string id { get; set; }
public SecureMediaEmbed secure_media_embed { get; set; }
public bool clicked { get; set; }
public bool stickied { get; set; }
public string author { get; set; }
public object media { get; set; }
public int score { get; set; }
public object approved_by { get; set; }
public bool over_18 { get; set; }
public bool hidden { get; set; }
public string thumbnail { get; set; }
public string subreddit_id { get; set; }
public object edited { get; set; }
public object link_flair_css_class { get; set; }
public object author_flair_css_class { get; set; }
public int downs { get; set; }
public bool saved { get; set; }
public bool is_self { get; set; }
public string permalink { get; set; }
public string name { get; set; }
public double created { get; set; }
public string url { get; set; }
public object author_flair_text { get; set; }
public string title { get; set; }
public double created_utc { get; set; }
public int ups { get; set; }
public int num_comments { get; set; }
public bool visited { get; set; }
public object num_reports { get; set; }
public object distinguished { get; set; }
public Replies replies { get; set; }
public int? gilded { get; set; }
public string parent_id { get; set; }
public string body { get; set; }
public string body_html { get; set; }
public string link_id { get; set; }
public bool? score_hidden { get; set; }
public int? count { get; set; }
public List<string> children { get; set; }
}
public class Child
{
public string kind { get; set; }
public Data2 data { get; set; }
}
public class Data
{
public string modhash { get; set; }
public List<Child> children { get; set; }
public object after { get; set; }
public object before { get; set; }
}
public class CommentsObject
{
public string kind { get; set; }
public Data data { get; set; }
}
}
Make your namespace correct!
Then handle the request and deserialise into a list of commentobjects: (u can use the webclient instead of httpclient if you want, this is just an example)
private HttpClient client;
public async Task<List<CommentsObject>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync("http://www.reddit.com/r/AskReddit/comments/1ut6xc.json");
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
List<CommentsObject> comments = await JsonConvert.DeserializeObjectAsync<List<CommentsObject>>(json);
return comments;
}
else
{
throw new Exception("Errorhandling message");
}
}
It's not ideal (and not completely an answer but more of a work around) but I created models that mock the reddit response json to make deserialization super easy. I use JsonProperty attributes on my model properties to pretty up the models a bit.
Here are the models
And since my models directly mock the json I can just use json.net's generic deserialize method.