Json DeserializeObject with whitespace in Resource Objects - c#

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

Related

Newtonsoft.Json returns incorrect values from file (with DeserializeObject)

I use json.net to get the values from the file and output them to the console. Here is the json file:
[
{
"id": 0,
"text": "aaa",
"speaker": "mike",
"next_node": 555,
"attached_script": "script"
},
{
"id": 1,
"text": "bbb",
"speaker": "tom",
"next_node": 2,
"attached_script": ""
}
]
Here is my main code (I use a separate class to get all the values of the corresponding structure):
public class PhraseNode
{
public int id { get; set; }
public string text { get; set; }
public string speaker { get; set; }
public int nextnode { get; set; }
public string addscript { get; set; }
}
internal class Program
{
static void RunDialog(string path)
{
using (StreamReader sr = new StreamReader(path))
{
string json = sr.ReadToEnd();
List<PhraseNode> nodes = JsonConvert.DeserializeObject<List<PhraseNode>>(json);
Console.WriteLine("Кол-во фраз: " + nodes.Count);
Console.Write(nodes[0].speaker + ": ");
Console.WriteLine(nodes[0].text);
Console.WriteLine(nodes[0].nextnode.ToString());
Console.WriteLine(nodes[0].addscript);
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
RunDialog("D:\\json1.json");
Console.WriteLine("press any key...");
Console.ReadKey();
}
}
The "speaker" and "text" strings are output normally, but instead of the "nextnode" value (555), 0 is output, and an empty string is output instead of "addscript". What's the problem here? I will be grateful for any help.
Serialize can't match the name json properties names next_node and attached_script to the corresponding class properties. You can use JsonPropertyAttribute to help it:
public class PhraseNode
{
public int id { get; set; }
public string text { get; set; }
public string speaker { get; set; }
[JsonProperty("next_node")]
public int nextnode { get; set; }
[JsonProperty("attached_script")]
public string addscript { get; set; }
}
Or provide the naming policy to the serializer:
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
List<PhraseNode> nodes = JsonConvert.DeserializeObject<List<PhraseNode>>(json, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
P.S. I recommend using standard naming conventions so make properties names pascal case.
your json properties and c# class properties should be the same. I recommend to use JsonProperty attributes
public partial class PhraseNode
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("speaker")]
public string Speaker { get; set; }
[JsonProperty("next_node")]
public long NextNode { get; set; }
[JsonProperty("attached_script")]
public string AttachedScript { get; set; }
}

Can't get data to object

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

How to set up class for json?

I am working with opentdb.com api and have no idea how to access data in this json:
{
"response_code":0,
"results": [
{
"category":"Animals",
"type":"multiple",
"difficulty":"easy",
"question":"What is the scientific name for modern day humans?",
"correct_answer":"Homo Sapiens",
"incorrect_answers":[
"Homo Ergaster",
"Homo Erectus",
"Homo Neanderthalensis"
]
},
{
"category":"Entertainment: Cartoon & Animations",
"type":"multiple",
"difficulty":"easy",
"question":"Who voices for Ruby in the animated series RWBY?",
"correct_answer":"Lindsay Jones",
"incorrect_answers":[
"Tara Strong",
"Jessica Nigri",
"Hayden Panettiere"
]
}
]
}
I am using Newtonsoft.Json and i tried this with only 1 Question but im geting an error that says that key value is wrong..
class Trivia
{
public Trivia(string json)
{
JObject jObject = JObject.Parse(json);
JToken jresults = jObject["results"];
category = (string)jresults["category"];
type = (string)jresults["type"];
difficulty = (string)jresults["difficulty"];
question = (string)jresults["question"];
correct_answer = (string)jresults["correct_answer"];
incorrect_answers = jresults["incorrect_answers"].ToArray();
}
public string category { get; set; }
public string type { get; set; }
public string difficulty { get; set; }
public string question { get; set; }
public string correct_answer { get; set; }
public Array incorrect_answers { get; set; }
}
Copy from json text and in new class in visual studio Edit-->Paste Special-->Paste JSON As Classes
public class Rootobject
{
public int response_code { get; set; }
public Result[] results { get; set; }
}
public class Result
{
public string category { get; set; }
public string type { get; set; }
public string difficulty { get; set; }
public string question { get; set; }
public string correct_answer { get; set; }
public string[] incorrect_answers { get; set; }
}
using namespace
using Newtonsoft.Json;
response is value get from your service
var outdeserialized = JsonConvert.DeserializeObject<Rootobject>(response);

How to do json data list<T> show dataGridView

I'm using the Newtonsoft library for parsing JSON:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
I have my json string and "MyClass" class.
JSON string:
{
"Result":
{
"MyClassList": [
{"Id":1,"Amount":"5,00"},
{"Id":2,"Amount":"10,00"},
{"Id":3,"Amount":"20,00"},
{"Id":4,"Amount":"25,00"}
]
"ReturnValues":
{
"ErrorCode":1,
"ErrorDescription":"Successful"
}
}
}
My Class:
public class MyClass
{
[JsonProperty("Id")]
Int64 Id { get; set; }
[JsonProperty("Amount ")]
string Amount { get; set; }
}
I am getting json data using these classes "GetMyClassList", "RootObject" and "ReturnValues".
List<MyClass> GetMyClassList()
{
JObject jo = new JObject();
List<MyClass> myClassList = new List<MyClass>();
jo.Add("Name", "Name");
jo.Add("Surname", "Surname");
url = "MyUrl";
string responseText = ExecuteHttpRequest(url , "POST",
"application/json", Encoding.UTF8.GetBytes(jo.ToString()), 3000);
myClassList = JsonConvert.DeserializeObject<RootObject>(responseText)
.GetMyClassListResult.MyClassList;
return myClassList;
}
public class ReturnValues
{
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
public class GetMyClassListResult
{
[JsonProperty("MyClassList")]
public List<MyClass> MyClassList { get; set; }
public ReturnValues ReturnValues { get; set; }
}
public class RootObject
{
public GetMyClassListResult GetMyClassListResult { get; set; }
}
I cannot get this data array (Id and amount).
and I want to take this data and show it in a dataGridView.
The best way to t-shoot this is set breakpoint at the line, where u getting the results from method -> is it filled? This Line:
return myClassList;
I have run Your code with single adjustment -> I have just used the direct JSON (not from web) - code below. This run without issues and I can see all the results parsed out of the JSON.
You have to find if the issue is parsin the JSON, or setting the data to the DataGridTable (which code You have not included at all).
class Program
{
static void Main(string[] args)
{
var result = new Program().GetMyClassList();
foreach (var item in result)
Console.WriteLine($"ID: {item.Id}\tAmount:{item.Amount}");
Console.ReadKey();
}
public List<MyClass> GetMyClassList()
{
List<MyClass> myClassList = new List<MyClass>();
string responseText = "{\"GetMyClassListResult\":{\"MyClassList\":[{\"Id\":1,\"Amount\":\"5,00\"},{\"Id\":2,\"Amount\":\"10,00\"},{\"Id\":3,\"Amount\":\"20,00\"},{\"Id\":4,\"Amount\":\"25,00\"}],\"ReturnValues\":{\"ErrorCode\":1,\"ErrorDescription\":\"Successful\"}}}";
myClassList = JsonConvert.DeserializeObject<RootObject>(responseText)
.GetMyClassListResult.MyClassList;
return myClassList;
}
}
public class MyClass
{
[JsonProperty("Id")]
public Int64 Id { get; set; }
[JsonProperty("Amount")]
public string Amount { get; set; }
}
public class ReturnValues
{
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
public class GetMyClassListResult
{
[JsonProperty("MyClassList")]
public List<MyClass> MyClassList { get; set; }
public ReturnValues ReturnValues { get; set; }
}
public class RootObject
{
public GetMyClassListResult GetMyClassListResult { 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