I am helpless, I need deserialize JSON string in this format to class.
JSON string:
{
"newNickInfo": {
"2775040": {
"idUser": 2775040,
"nick": "minci88",
"sefNick": "minci88",
"sex": 2,
"photon": "http:\/\/213.215.107.125\/fotky\/277\/50\/n_2775040.jpg?v=4",
"photos": "http:\/\/213.215.107.125\/fotky\/277\/50\/s_2775040.jpg?v=4",
"logged": false,
"idChat": 0,
"roomName": "",
"updated": 1289670130
}
}
}
Class:
public class User
{
public string idUser { get; set; }
public string nick { get; set; }
public string sefNick { get; set; }
public string sex { get; set; }
public string photon { get; set; }
public string photos { get; set; }
public bool logged { get; set; }
public int idChat { get; set; }
public string roomName { get; set; }
public string updated { get; set; }
}
First problem is, class properties must be lower case, and second problem is I try many ways but I don’t know how cut json object from this json string and deserialize in class.
Any ides? Thank for any help.
One more question, what format would have c# class, if I want deserialize this json string into it.
looks like your JSON string is not correct. Look at this
string json = #"[
{
"newNickInfo": "2775040",
"idUser": "2775040",
"nick":"minci88",
"sefNick":"minci88",
"sex":2,
"photon":"http:\/\/213.215.107.125\/fotky\/277\/50\/n_2775040.jpg?v=4",
"photos":"http:\/\/213.215.107.125\/fotky\/277\/50\/s_2775040.jpg?v=4",
"logged":false,
"idChat":0,
"roomName":"",
"updated":"1289670130"
}
]";
public class User
{
[JsonProperty]
public string idUser{get;set;}
[JsonProperty]
public string nick{get;set;}
[JsonProperty]
public string sefNick{get;set;}
[JsonProperty]
public string sex{get;set;}
[JsonProperty]
public string photon{get;set;}
[JsonProperty]
public string photos{get;set;}
[JsonProperty]
public bool logged{get;set;}
[JsonProperty]
public int idChat{get;set;}
[JsonProperty]
public string roomName{get;set;}
[JsonProperty]
public string updated{get;set;}
}
List<User> users = JsonConvert.DeserializeObject<List<User>>(json);
User u1 = users[0];
Console.WriteLine(u1.nick);
using System.Web.Script.Serialization;
var serializer = new JavaScriptSerializer();
var deserialized = serializer.Deserialize<Dictionary<string, Dictionary<string, User>>>(theJsonString);
var theUser = deserialized["newNickInfo"]["2775040"];
I use this tool Jsonclassgenerator. It could generate C# classes for the input Json string. You dont have to use the exact class generated. But you can see the format of the class and create a similar one in your project.
Related
I am using this code to read a json file firstSession.json and display it on a label.
var assembly = typeof(ScenarioPage).GetTypeInfo().Assembly;
string jsonFileName = "firstSession.json";
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
using (var reader = new StreamReader(stream))
{
var json = reader.ReadToEnd(); //json string
var data = JsonConvert.DeserializeObject<SessionModel>(json);
foreach (SessionModel scenario in data)
{
scenarioName.Text = scenario.title;
break;
}
scenarioName.Text = data.title; // scenarioName is the name of the label
}
SessionModel.cs looks like:
public class SessionModel : IEnumerable
{
public int block { get; set; }
public string name { get; set; }
public string title { get; set; }
public int numberMissing { get; set; }
public string word1 { get; set; }
public string word2 { get; set; }
public string statement1 { get; set; }
public string statement2 { get; set; }
public string question { get; set; }
public string positive { get; set; } // positive answer (yes or no)
public string negative { get; set; } // negative answer (yes or no)
public string answer { get; set; } // positive or negative
public string type { get; set; }
public string format { get; set; }
public string immersion { get; set; }
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
The beginning of my json is:
{
"firstSession": [
{
"block": 1,
"name": "mark",
"title": "mark's house",
"numberMissing": 1,
"word1": "distracted",
"word2": "None",
"statement1": "string 1",
"statement2": "None",
"question": "question",
"positive": "No",
"negative": "Yes",
"answer": "Positive",
"type": "Social",
"format": "Visual",
"immersion": "picture"
},
I am getting a Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object into type "MyProject.SessionModel" because the type requires a JSON array to deserialize correctly. To fix this error either change the JSON to a JSON array or change the deserialized type so that it is a normal .NET type that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'firstSession', line 2, position 17.
How can I convert the json string to a json array? Or make one of the other modifications the debugger suggests?
you need to create a wrapper class (json2csharp.com will help you do this)
public class Root {
public List<SessionModel> firstSession { get; set; }
}
then
var data = JsonConvert.DeserializeObject<Root>(json);
data.firstSession will be a List<SessionModel>
Create a new Class and have firstSession as List of SessionModel.
public class Sessions
{
public List<SessionModel> firstSession { get; set; }
}
Remove IEnumerable from the SessionModel
public class SessionModel
{
public int block { get; set; }
public string name { get; set; }
public string title { get; set; }
}
Change thedeserialization part as follows
var data = JsonConvert.DeserializeObject(line);
foreach (SessionModel scenario in data.firstSession)
{
//Here you can get each sessionModel object
Console.WriteLine(scenario.answer);
}
I am new to C# need help to convert json Object to Array
convert this json
[
{
"Id": 1000,
"Name": "May",
"Address": "odyssey",
"Country": "USA",
"Phone": "12345"
}
]
To
var details = {1000,May,odyssey,USA,12345};
Use Newtonsoft.Json to deserialize JSON to a specified .net type. You can deserialize to a class too, see below:
public class Person
{
public int Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public string Phone {get;set;}
}
var details = JsonConvert.DeserializeObject<Person>(json);
You are going to have to deserialize the Json String. Deserialize into array of objects.
JavaScriptSerializer js = new JavaScriptSerializer();
yourClass[] items = js.Deserialize<Yourclass[]>(yourJSONcontent);
Steps:
1. Create Model.
2. Get Data in string
3.Deserialize Object
And if you are confused How to create C# model from the json then use this link.
https://app.quicktype.io
Use This Model.
public class Test
{
[JsonProperty("Id")]
public long Id { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Address")]
public string Address { get; set; }
[JsonProperty("Country")]
public string Country { get; set; }
[JsonProperty("Phone")]
[JsonConverter(typeof(ParseStringConverter))]
public long Phone { get; set; }
}
string data="Your Json String"
var details = JsonConvert.DeserializeObject<Test>(data);
To make a list from your json values you can use a JObject, you don't have to know the objects stored in your Json in contrary to the others question.
JObject myObject = JsonConvert.DeserializeObject<JObject>(myJson);
List<object> myList = new List<object>();
foreach (var element in myObject)
{
myList.Add(element.Value);
}
If you already know what your json is made of, you can create a class that represent your object and implement the interface IEnumerable.
var myObject = JsonConvert.DeserializeObject<MyClass>(myJson);
var myArray = myObject2.ToArray():
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public int Phone { get; set; }
public object[] ToArray()
{
return new object[]
{
Id,
Name,
Address,
Country,
Phone
};
}
}
NB : the variable myJson in the previous codes is a string that represent your json as var myJson = "{\"Id\": 1000,\"Name\": \"May\",\"Address\": \"odyssey\",\"Country\": \"USA\",\"Phone\": \"12345\"}";
This is json:
{
"odata.metadata": ".....",
"value": [
{
"AbsEntry": 10,
"ItemNo": "....",
"UoMEntry": -1,
"Barcode": "2000000000022",
"FreeText": "Ean13"
}
]
}
This is class:
public class BarCode
{
public int AbsEntry { get; set; }
public string ItemNo { get; set; }
public string Barcode { get; set; }
public string FreeText { get; set; }
}
This method return null:
BarCode barcode = JsonParser.DeserializeObjcet<BarCode>(json);
Are there any properties or other that can cause the call DeserializeObject to deserialize me only the fields of my classes (the names are exactly those of the Json)?
You need to create class like below not BarCode
public class Value
{
public int AbsEntry { get; set; }
public string ItemNo { get; set; }
public int UoMEntry { get; set; }
public string Barcode { get; set; }
public string FreeText { get; set; }
}
or you can change the JSON format
"BarCode": [
{
"AbsEntry": 10,
"ItemNo": "....",
"UoMEntry": -1,
"Barcode": "2000000000022",
"FreeText": "Ean13"
}
]
The structure of your class should match the structure of your JSON if you want the deserialization to succeed.
If you want a partial deserialization e.g. only deserializing the values property into your class you can use this code:
JObject jObject = JObject.Parse(json);
BarCode barcode = jObject["values"].Children().First().ToObject<BarCode>();
With this solution you don't need to refactor your class or adding a new one.
You are missing the root object :
public class RootObject
{
public string __invalid_name__odata.metadata { get; set; }
public List<BarCode> value { get; set; }
}
note that the invalid name oprperty can just be remove so it will be igrored!
Even if you want only the Value part you will have to deserialise from the root, then navigate to the child properties you need.
How can we parse if json fields contains a colon(:)? Like this:
{
"dc:creator":"Jordan, Micheal",
"element:publicationName":"Applied Ergonomics",
"element:issn":"2839749823"
}
In fact I wonder how to do this with a library like restsharp, for mapping?
Using Json.Net
string json = #"{
""dc:creator"":""Jordan, Micheal"",
""element:publicationName"":""Applied Ergonomics"",
""element:issn"":""2839749823""
}";
var pub = JsonConvert.DeserializeObject<Publication>(json);
public class Publication
{
[JsonProperty("dc:creator")]
public string creator { set; get; }
[JsonProperty("element:publicationName")]
public string publicationName { set; get; }
[JsonProperty("element:issn")]
public string issn { set; get; }
}
OR
Console.WriteLine(JObject.Parse(json)["dc:creator"]);
If you use DataContractJsonSerializer, DataMemberAttribute has property Name which can be used to override default name. This means that when you deserialize json value of property dc:creator is assigned to Publication::Creator property and on the contrary when you serialize C# object.
For example:
public class Publication
{
[DataMember(Name="dc:creator")]
public string Creator { set; get; }
[DataMember(Name="element:publicationName")]
public string PublicationName { set; get; }
[DataMember(Name="element:issn")]
public string Issn { set; get; }
}
If you choose to use Json.Net, #L.B's answer is the way to go.
I want to deserialize a Json string from a php website. Unfortunately every time I try it, it will return null for medianPrice....Why?
public class PriceInfo
{
public string success { get; set; }
public double lowestPrice { get; set; }
public string volume { get; set; }
public string medianPrice { get; set; }
}
WebClient client = new WebClient();
string url = "http://steamcommunity.com/market/priceoverview/?country=US¤cy=1&appid=730&market_hash_name=" + name;
byte[] html = client.DownloadData(url);
UTF8Encoding utf = new UTF8Encoding();
string return_value = utf.GetString(html);
PriceInfo priceInfo = new JavaScriptSerializer().Deserialize<PriceInfo>(return_value);
if( Double.Parse(priceInfo.medianPrice) > 0.15 )
{
string blablu = "hello";
}
The Json which returns from the website is the following:
{"success":true,"lowest_price":"$0.04","volume":"3,952","median_price":"$0.02"}
I hope you can help me!
I am strongly recommending that you try using Newtonsoft.Json
you will find that it is easier to handle your Jason objects
your code will be like this (Untested)
PriceInfo defaultCallResult = JsonConvert.DeserializeObject<PriceInfo>(return_value);
Your JSON property is named "median_price" (with an underscore), but your C# property is "medianPrice".
You could use Json.NET which will allow you to change the mapping using attributes.
Using Json.NET, decorate your medianPrice property as follows:
[JsonProperty(PropertyName = "median_price")]
public string medianPrice { get; set; }
I'm not sure how JavaScriptSerializer succeeds in parsing your class at all, as the keys hardly match match the class properties.
JavaScriperSerializer is obsolete, I'd recommend you use another serializer, such as Json.NET:
public class PriceInfo
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("lowest_price")]
public double LowestPrice { get; set; }
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("median_price")]
public string MedianPrice { get; set; }
}
And when you want to deserialize:
PriceInfo priceInfo = JsonConvert.DeserializeObject<PriceInfo>(returnValue);
First of all, as mentioned in the other answers, your property names do not match.
So take
public class PriceInfo
{
public string success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
edit: as mentioned by Yuval, you cannot use JsonProperty with JavaScriptSerializer so you need to stick with the property names from the json.
Then, there is currency information in the json. So you need to get rid of these:
string return_value = "{\"success\":true,\"lowest_price\":\"$0.04\",\"volume\":\"3,952\",\"median_price\":\"$0.02\"}";
string return_valueconverted = HttpUtility.HtmlDecode(return_value);
PriceInfo priceInfo = new JavaScriptSerializer().Deserialize<PriceInfo>(return_valueconverted);
priceInfo.lowest_price = priceInfo.lowest_price.TrimStart('$');
priceInfo.median_price = priceInfo.median_price.TrimStart('$');
As you can see, this does HtmlDecode these values and afterwards trims the dollar sign from the value.
See more about Html character set here:
http://www.w3.org/MarkUp/html-spec/html-spec_13.html