I am stuck on a json deserialization, it seems that there's something I can't catch on this json :
{
"success" : true,
"message" : "",
"result" : [{
"Currency" : "DOGE",
"Balance" : 0.00000000,
"Available" : 0.00000000,
"Pending" : 0.00000000,
"CryptoAddress" : "DLxcEt3AatMyr2NTatzjsfHNoB9NT62HiF",
"Requested" : false,
"Uuid" : null
}, {
"Currency" : "BTC",
"Balance" : 14.21549076,
"Available" : 14.21549076,
"Pending" : 0.00000000,
"CryptoAddress" : "1Mrcdr6715hjda34pdXuLqXcju6qgwHA31",
"Requested" : false,
"Uuid" : null
}
]
}
Here is the code I am trying :
if (stream == null) return account;
var re = new StreamReader(stream);
var json = re.ReadToEnd();
var jobj = (JObject)JsonConvert.DeserializeObject(json);
var items = jobj.Children()
.Cast<JProperty>()
.Select(j => new
{
ID = j.Name,
Other = (string)j.Value["Currency"]
})
.ToList();
But unfortunately, nothing happens with this code, and I'm quite stuck as to why. After searching around here, and trying several other solutions found on similar thread, this one is the closest I could get to deseraliaze my string.
I have two class I wish to fill in with this json :
public class AccountCurrencies
{
public string Jsonid { get; set; }
public string Currency { get; set; }
public double Balance { get; set; }
public double Available { get; set; }
public double Pending { get; set; }
public string CryptoAddress { get; set; }
public bool Requested { get; set; }
public object Uuid { get; set; }
}
public class AccountWrapper
{
public bool Success { get; set; }
public string Message { get; set; }
public List<AccountCurrencies> AccountAllCurrencies { get; set; }
}
You are missing two things here. Firstly to get the Json into your class structure is a single line of code:
var yourObject = JsonConvert.DeserializeObject<AccountWrapper>(json);
Secondly, you need to tell the serialiser the the AccountAllCurrencies property is called "result" in the Json data. To do this, use the JsonProperty attribute:
public class AccountWrapper
{
public bool Success { get; set; }
public string Message { get; set; }
//Add this line
[JsonProperty("result")]
public List<AccountCurrencies> AccountAllCurrencies { get; set; }
}
Related
I'm trying to call a web API (JSON/Csharp Console application) I did the same steps in the dotnet : https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient
However, when I'm trying to get only the property "NAME1", an error came up : The JSON value could not be converted to System.Collections.Generic.List. I could get all the json information but when Deserializing the result for getting only particular data such as NAME1 it doesn't work.
public partial class Result
{
public List<GAZETTEER_ENTRY> GAZETTEER_ENTRY { get; set; }
}
public partial class GAZETTEER_ENTRY
{
public string ID { get; set; }
public string NAME1 { get; set; }
}
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
await RunAsync();
}
private static async Task RunAsync()
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("key", "xxxxxx");
var streamTask = client.GetStreamAsync("https://api.os.uk/search/names/v1/find?query=coventry&fq=LOCAL_TYPE:Hospital");
var data = await JsonSerializer.DeserializeAsync<List<GAZETTEER_ENTRY>>(await streamTask);
foreach (var item in data)
{
Console.WriteLine(item.NAME1);
}
This is the JSON data:
"header" : {
"uri" : "https://api.os.uk/search/names/v1/find?query=coventry",
"query" : "coventry",
"format" : "JSON",
"maxresults" : 100,
"offset" : 0,
"totalresults" : 4134
},
"results" : [ {
"GAZETTEER_ENTRY" : {
"ID" : "osgb4000000074568994",
"NAMES_URI" : "http://data.ordnancesurvey.co.uk/id/4000000074568994",
"NAME1" : "Coventry",
"TYPE" : "populatedPlace",
"LOCAL_TYPE" : "City",
"COUNTRY" : "England",
}
}, {
"GAZETTEER_ENTRY" : {
"ID" : "osgb4000000019401618",
"NAMES_URI" : "http://data.ordnancesurvey.co.uk/id/4000000019401618",
"NAME1" : "Coventry Street",
"TYPE" : "transportNetwork",
"LOCAL_TYPE" : "Named Road",
"COUNTRY" : "England",
}
}, {
"GAZETTEER_ENTRY" : {
"ID" : "osgb4000000073321650",
"NAMES_URI" : "http://data.ordnancesurvey.co.uk/id/4000000073321650",
"NAME1" : "Coventry",
"TYPE" : "transportNetwork",
"LOCAL_TYPE" : "Railway Station",
"COUNTRY" : "England",
}
Try deserializing the json using this RootObject model:
public class RootObject
{
public ResultObject[] results { get; set; }
}
public class ResultObject
{
public GazetteerEntryObject GAZETTEER_ENTRY { get; set; }
}
public class GazetteerEntryObject
{
public string NAME1 { get; set; }
}
Do it this way
var data = await JsonSerializer.DeserializeAsync<RootObject>(await streamTask);
To retrieve the names, do it like this:
var names = data.results.Select(x => x.GAZETTEER_ENTRY.NAME1);
Your response classes should be like
public class SearchResult
{
public Header header { get; set; }
public List<Result> results { get; set; }
}
public class Header
{
public string uri { get; set; }
public string query { get; set; }
public string format { get; set; }
public int maxresults { get; set; }
public int offset { get; set; }
public int totalresults { get; set; }
}
public class Result
{
public GAZETTEER_ENTRY GAZETTEER_ENTRY { get; set; }
}
public class GAZETTEER_ENTRY
{
public string ID { get; set; }
public System.Uri NAMES_URI { get; set; }
public string NAME1 { get; set; }
public string TYPE { get; set; }
public string LOCAL_TYPE { get; set; }
public string COUNTRY { get; set; }
}
and the deserialize should be
var data = await JsonSerializer.DeserializeAsync<SearchResult>(await streamTask);
and access NAME1 of nth result
data.results[0].GAZETTEER_ENTRY.NAME1
if you find difficulty in comparing classes and json response, You can simply copy the json response and goto VS -> edit-> paste special -> paste json as classes. VS will auto generate classes for you.
I want to convert the following json string to a C# class. But i cant figure it out... even with a online converter programm like "json2csharp".
{[
{
"tmcp_post_fields": [],
"product_id": 703,
"per_product_pricing": true,
"cpf_product_price": "45",
"variation_id": false,
"form_prefix": "",
"tc_added_in_currency": "EUR",
"tc_default_currency": "EUR"
}
]}
Can someone help me?
I tried these false variations:
public class myclass
{
public List<object> tmcp_post_fields { get; set; }
public int product_id { get; set; }
public bool per_product_pricing { get; set; }
public string cpf_product_price { get; set; }
public bool variation_id { get; set; }
public string form_prefix { get; set; }
public string tc_added_in_currency { get; set; }
public string tc_default_currency { get; set; }
}
or a List of this class
List<myclass>
I use this code to convert it
if (value != null && value.GetType().FullName.StartsWith("Newtonsoft.Json"))
{
string s = value.GetType().FullName;
if (value.GetType().FullName.EndsWith("JArray"))
{
JArray ja = (JArray)Convert.ChangeType(value, typeof(JArray));
if (ja.HasValues)
{
try
{
return ja.ToObject<myclass>(); //this
return ja.ToObject<List<myclass>>(); //or this does NOT work for me
}
catch { }
return value;
}
else
return null;
}
I allway got this error:
Newtonsoft.Json.JsonReaderException - Error reading string. Unexpected
token
If I remove the first opening and closing {} it would work.
your json is not valid, it has extra {} on the sides. Try this
var json=...your json
json=json.Substring(1,json.Length-2);
var jsonDeserialized = JsonConvert.DeserializeObject<Data[]>(json);
and class
public class Data
{
public List<object> tmcp_post_fields { get; set; }
public int product_id { get; set; }
public bool per_product_pricing { get; set; }
public string cpf_product_price { get; set; }
public bool variation_id { get; set; }
public string form_prefix { get; set; }
public string tc_added_in_currency { get; set; }
public string tc_default_currency { get; set; }
}
Another option is to use insert string. This option is even better since you can use parse json string as well.
json=json.Insert(1,"result:");
var jsonDeserialized = JsonConvert.DeserializeObject<Root>(json);
and class
public class Root
{
public Data[] result {get; set;}
}
output
{
"result": [
{
"tmcp_post_fields": [],
"product_id": 703,
"per_product_pricing": true,
"cpf_product_price": "45",
"variation_id": false,
"form_prefix": "",
"tc_added_in_currency": "EUR",
"tc_default_currency": "EUR"
}
]
}
I'm trying to grap json data from mongodb, put it into a class objec and then print one parameter to console, but I get this error :
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: O. Path '_id', line 1, position 10.'
My json looks like this:
{ "_id" : ObjectId("5d72b79c58011725b8b31b10"), "length" : NumberLong(957608), "
chunkSize" : 64512, "uploadDate" : ISODate("2019-09-06T19:46:42.058Z"), "md5" :
"3965979118e1302a7d19f609f38ede3e", "filename" : "C:\\Users\\kbu\\Downloads\\hve
m-er-vi.jpg", "metadata" : { "Beloeb" : "", "Overskrift" : "", "Gruppe" : "", "B
eskrivelse" : "", "Dato" : "6. september 2019", "Afsender" : "Lars" } }
I suspect, it has to do with my class, but I can't figure out what.
This is my code:
class Program
{
static void Main(string[] args)
{
var client = new MongoClient("mongodb+srv://*********:*********#kbucluster-oslh9.mongodb.net/test?retryWrites=true&w=majority");
var database = client.GetDatabase("test");
var collec = database.GetCollection<BsonDocument>("fs.files");
var filter = Builders<BsonDocument>.Filter.Empty;
var result = collec.Find(filter).ToList();
foreach(var doc in result)
{
Console.WriteLine(doc.ToJson());
RootObject bilag = JsonConvert.DeserializeObject<RootObject>(doc.ToJson());
Console.WriteLine(bilag.ID);
}
Console.ReadKey();
}
}
public class Metadata
{
public string Beloeb { get; set; }
public string Overskrift { get; set; }
public string Gruppe { get; set; }
public string Beskrivelse { get; set; }
public string Dato { get; set; }
public string Afsender { get; set; }
}
public class RootObject
{
public string ID { get; set; }
public string Length { get; set; }
public string ChunkSize { get; set; }
public string UploadDate { get; set; }
public string MD5 { get; set; }
public string Filename { get; set; }
public Metadata Metadata { get; set; }
}
}
You can use the following method
object dotnetObject = BsonTypeMapper.MapToDotNetValue(bsonDocument);
// Json mapped to default .Net objects
string json = Newtonsoft.Json.JsonConvert.SerializeObject(dotnetObject);
// Parsing as JObject
var jobject = JObject.Parse(json);
// Deserializing as your custom Type
var myObject = JsonConvert.DeserializeObject<MyType>(json);
you don't need json.net if you match the property names/types of the RootObject like this:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;
namespace StackOverflow
{
public class Program
{
public class Metadata
{
public string Beloeb { get; set; }
public string Overskrift { get; set; }
public string Gruppe { get; set; }
public string Beskrivelse { get; set; }
public string Dato { get; set; }
public string Afsender { get; set; }
}
public class RootObject
{
[BsonId] // need to add this
public ObjectId ID { get; set; }
public int length { get; set; }
public double chunkSize { get; set; }
public DateTime uploadDate { get; set; }
public string md5 { get; set; }
public string filename { get; set; }
public Metadata metadata { get; set; }
}
private static void Main(string[] args)
{
var collection = new MongoClient("mongodb://localhost")
.GetDatabase("test")
.GetCollection<RootObject>("fs.files");
var result = collection.Find(Builders<RootObject>.Filter.Empty).ToList();
foreach (var doc in result)
{
Console.WriteLine(doc.ToJson());
Console.WriteLine("");
Console.WriteLine(doc.ID.ToString());
Console.Read();
}
}
}
}
You can't have functions in your JSON
"_id" :ObjectId("5d72b79c58011725b8b31b10"), "length" : NumberLong(957608),"uploadDate" : ISODate("2019-09-06T19:46:42.058Z")
Parse error on line 1:
{ "_id" : ObjectId("5d72b79c58
----------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
1-Wrong value _id key : "what is ObjectId method in json"?
2-wrong name _id : beacause in RootObject class ,property is ID!
3- you must remove ObjectId , NumberLong , ISODate With their braces
{ "ID" : "5d72b79c58011725b8b31b10", "Length" : "957608", "
ChunkSize" : "64512", "UploadDate" : "2019-09-06T19:46:42.058Z", "MD5" :
"3965979118e1302a7d19f609f38ede3e", "FileName" : "C:\\Users\\kbu\\Downloads\\hve
m-er-vi.jpg", "Metadata" : { "Beloeb" : "", "Overskrift" : "", "Gruppe" : "", "B
eskrivelse" : "", "Dato" : "6. september 2019", "Afsender" : "Lars" } }
I'm trying to parse a Json that contains a lot of objects.
.json look like this:
:
{
"status" : "success",
"prices" : [
{
"market_hash_name" : "4X4 Car",
"price" : "7.87",
"created_at" : 1472587613
},
{
"market_hash_name" : "Yellow Car",
"price" : "27.75",
"created_at" : 1472519899
}
[...] etc
and I just want to get the price of specific market hash name. How can I do that?
I have got this atm
using System.IO;
using Newtonsoft.Json;
public class MarketHandler
{
//Methods
public MarketHandler updatePrices()
{
var json = File.ReadAllText("PriceSkins.json");
currentPrices = JsonConvert.DeserializeObject<Data>(json);
return this;
}
public Data currentPrices { get; set; }
public class Data
{
public Response response { get; set; }
}
public class Response
{
public string status { get; set; }
public Price prices { get; set; }
}
public class Price
{
public string market_hash_name { get; set; }
public string price { get; set; }
public int created_at { get; set; }
}
You can do like this, place your JSON some where else on your system and load the JSON like below
Rootobject ro = new Rootobject();
StreamReader sr = new StreamReader(Server.MapPath("text.json"));
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<Rootobject>(jsonString);
Before that you have to create the classes like below these classes are matching your JSON, already I have answer similar this question here you can cehck how to create classes for JSON easily
public class Rootobject
{
public string status { get; set; }
public Price[] prices { get; set; }
}
public class Price
{
public string market_hash_name { get; set; }
public string price { get; set; }
public int created_at { get; set; }
}
After that,from the instance of the Rootobject(ro) you can access the price like below
Price[] price_list = ro.prices;
{
"transactionId" : XXXXX,
"uri" : "https://XXX.XXXXXXXX.XXXX/XXX/XXX",
"terminalId" : 1,
"action" : "CHARGE",
"amountBase" : "3.00",
"amountTotal" : "3.00",
"status" : "CAPTURE",
"created" : "2015-01-24T07:24:10Z",
"lastModified" : "2015-01-24T07:24:10Z",
"response" :
{
"approved" : true,
"code" : "00",
"message" : "Approved",
"processor" :
{
"authorized" : true,
"approvalCode" : "XXXX",
"avs" :
{
"status" : "NOT_REQUESTED"
},
}
},
"settlement" :
{
"settled" : false
},
"vault" :
{
"type" : "CARD",
"accountType" : "VISA",
"lastFour" : "1111"
}
}
I see this has got a lot of down votes but no one is actually offering any advice. The json above is not a natural fit for a Dictionary but should be de-serialized into an object.
Response, settlement and vault all have their own properties and as such should be their own objects.
Look into Json.net for a good way to convert json into your c# objects. If you are stuck on how you would represent this object in C# then you need to read a good book on programming specifically one that covers Object Orientated programming.
Stack is a great resource for these questions but you need to try and show you have done your own research first otherwise others will just mark your questions down.
Are you receiving a POST that contains a JSON ?
You can use something like this , create an instance of Request class and assign the JSON obj to that instance. You should be able to access the parameters via request instance.
The basic structure will look some thing like this :
public class Request
{
public Int64 transactionId { get; set; }
public string uri { get; set; }
public int terminalId { get; set; }
public string action { get; set; }
public string amountBase { get; set; }
public int amountTotal { get; set; }
public string status { get; set; }
public DateTime created { get; set; }
public DateTime lastModified { get; set; }
public Response response { get; set; }
public Settlement settlement { get; set; }
public Vault vault { get; set; }
}
public class Response
{
public bool approved { get; set; }
public int code { get; set; }
public string message { get; set; }
public Processor processor { get; set; }
}
public class Processor
{
public bool authorized { get; set; }
public string approvedCode { get; set; }
public AVS avs { get; set; }
}
public class AVS
{
public string status { get; set; }
}
public class Settlement
{
public bool settled { get; set; }
}
public class Vault
{
public string type { get; set; }
public string accountType { get; set; }
public string lastFour { get; set; }
}
Hope this helps !!