Can't get data to object - c#

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" } }

Related

Calling a Web API to get particular information using DeserializineAsync (JSON/ C#)

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.

Read and parse Json on c# and get specific values

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;

Json String that doesn't want to be deserialized

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; }
}

Json DeserializeObject with whitespace in Resource Objects

The JSON string contains a whitespace in the Resource Objects so 'id' is filled, but 'use id' 'userstatus' 'last event' are null.
I tried 3 different ways in my class but none of them works()
Underscore
With whitespace
Without whitespace
My code(c#):
this is the JSON string
{
"resultsList":[
{
"id":"1",
"last event":"Mar 20 07:08 AM",
"use id":"142AD",
"user status":"offline"
},
{
"id":"2",
"last event":"Mar 19 08:07 AM",
"use id":"1426BD",
"user status":"offline"
}
]
}
I Deserialize the JSON in
Results.cs(form)
string url = "API url";
var json = new WebClient().DownloadString(url);
var results = JsonConvert.DeserializeObject<Rootobject>(json);
Sessions.cs(class)
public class Rootobject
{
public Resultslist[] resultsList { get; set; }
}
public class Resultslist
{
public int id { get; set; }
public string last event { get; set; }
public string use_id { get; set; }
public string userstatus { get; set; }
}
The simplest approach in your case would be:
string json = "{\"resultsList\":[{\"id\":\"1\",\"last event\":\"Mar 20 07:08 AM\",\"use id\":\"142AD\",\"user status\":\"offline\"},{\"id\":\"2\",\"last event\":\"Mar 19 08:07 AM\",\"use id\":\"1426BD\",\"user status\":\"offline\"}]}";
dynamic o = JsonConvert.DeserializeObject(json);
var result = o["resultsList"][0]["last event"];
Try this:
using System;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var json = #"{""resultsList"":[{ ""id"":""1"",""last_event"":""Mar 20 07:08 AM"",""use_id"":""142AD"",""user_status"":""offline""}, { ""id"":""2"",
""last_event"":""Mar 19 08:07 AM"",
""use_id"":""1426BD"",
""user_status"":""offline""
}
]
}";
var results = JsonConvert.DeserializeObject<Rootobject>(json);
for (int i = 0; i < results.resultsList.Length; i++)
{
Console.WriteLine("Id:" + results.resultsList[i].id);
Console.WriteLine("Last Event:" + results.resultsList[i].last_event);
Console.WriteLine("User ID:" + results.resultsList[i].use_id);
Console.WriteLine("User Status:" + results.resultsList[i].user_status);
}
Console.ReadKey();
}
}
public class Rootobject
{
public Resultslist[] resultsList { get; set; }
}
public class Resultslist
{
public int id { get; set; }
public string last_event { get; set; }
public string use_id { get; set; }
public string user_status { get; set; }
}
}
Sessions.cs(class)
I added a JsonProperty and it works.
public class Rootobject
{
public Resultslist[] resultsList { get; set; }
}
public class Resultslist
{
public int id { get; set; }
[JsonProperty("last event")]
public string lastevent { get; set; }
[JsonProperty("use id")]
public string useid { get; set; }
[JsonProperty("user status")]
public string userstatus { get; set; }
}

Read data from Dictionary

I am facing a problem for parsing a JSON array in C#
{
"details" : [{
"state" : "myState1",
"place" : [{
"name" : "placeName",
"age" : 13
}
]
}, {
"state" : "myState2",
"place" : [{
"name1" : "placeName"
}
]
}, {
"state" : "myState3",
"place" : [{
"name2" : "placeName"
}
]
}
]
}
My code is:
static void Main(string[] args)
{
string txt = File.ReadAllText("MyJSONFile.txt");
JavaScriptSerializer ser = new JavaScriptSerializer();
var data = ser.Deserialize(txt);
}
public class Wrap
{
public List<Dictionary<string, object>> details { get; set; }
}
How can I read data from these dictionaries? Sometimes the JSON will include only 1 facility's details, but other times there are more than 30 items in the array. This data is being pulled from the database.
You may use the following C# classes structure:
public class Place
{
public string name { get; set; }
public int age { get; set; }
public string name1 { get; set; }
public string name2 { get; set; }
}
public class Detail
{
public string state { get; set; }
public List<Place> place { get; set; }
}
public class Root
{
public List<Detail> details { get; set; }
}
public class Program
{
static void Main(string[] args)
{
string txt = File.ReadAllText("MyJSONFile.txt");
JavaScriptSerializer ser = new JavaScriptSerializer();
var data = ser.Deserialize<Root>(txt);
Console.WriteLine(data.details.Count); // 3
Console.WriteLine(data.details[0].state); // myState1
Console.WriteLine(data.details[1].place.Count); // 1
Console.WriteLine(data.details[1].place[0].age); // 13
}
}
The class structure you are using is wrong.
You will have to use the structure as follows, which corresponds to your JSON.
This structure have been generated using json2csharp
public class Place
{
public string name { get; set; }
public int age { get; set; }
public string name1 { get; set; }
public string name2 { get; set; }
}
public class Detail
{
public string state { get; set; }
public List<Place> place { get; set; }
}
public class RootObject
{
public List<Detail> details { get; set; }
}
Now in your code you can de serialize this using Newtonsoft.Json as follows:
static void Main(string[] args)
{
string jsonText = System.IO.File.ReadAllText("MyJSONFile.txt");
var rootObj = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonText);
rootObj.details.ForEach(detail =>
{
Console.WriteLine(detail.state);
detail.place.ForEach(p =>
{
if (string.IsNullOrWhiteSpace(p.name) == false)
{
Console.WriteLine(p.name);
}
if (string.IsNullOrWhiteSpace(p.name1) == false)
{
Console.WriteLine(p.name1);
}
if (string.IsNullOrWhiteSpace(p.name2) == false)
{
Console.WriteLine(p.name2);
}
if (p.age > 0)
{
Console.WriteLine(p.age);
}
Console.WriteLine(string.Empty);
});
});
Console.ReadKey(true);
}

Categories

Resources