UsingJSON.netJsonConverterclass.
Section83.1:UsingJsonConverteronsimplevalues
Example using JsonCoverter to deserialize the runtime property from the api response into a TimespanObject in the Movies model
JSON(http://www.omdbapi.com/?i=tt1663662)
{
Title:”PacificRim”,
Year:”2013″,
Rated:”PG-13″,
Released:”12Jul2013″,
Runtime:”131min”,
Genre:”Action,Adventure,Sci-Fi”,
Director:”GuillermodelToro”,
Writer:”TravisBeacham(screenplay),GuillermodelToro(screenplay),TravisBeacham(story)”, Actors:”CharlieHunnam,DiegoKlattenhoff,IdrisElba,RinkoKikuchi”,
Plot:”As a war between humankind andmonstroussea creatures wages on, a formerpilotand a traineearepaireduptodriveaseeminglyobsoletespecialweaponinadesperateefforttosave theworldfromtheapocalypse.”,
Language:”English,Japanese,Cantonese,Mandarin”,
Country:”USA”,
Awards:”Nominatedfor1BAFTAFilmAward.Another6wins&46nominations.”, Poster:
“https://images-na.ssl-images-amazon.com/images/M/MV5BMTY3MTI5NjQ4Nl5BMl5BanBnXkFtZTcwOTU1OTU0OQ@@.
_V1_SX300.jpg”,
Ratings:[{
Source:”InternetMovieDatabase”,
Value:”7.0/10″
},
{
Source:”RottenTomatoes”,
Value:”71%”
},
{
Source:”Metacritic”,
Value:”64/100″
}
],
Metascore:”64″,
imdbRating:”7.0″,
imdbVotes:”398,198″,
imdbID:”tt1663662″,
Type:”movie”,
DVD:”15Oct2013″,
BoxOffice:”$101,785,482.00″,
Production:”WarnerBros.Pictures”,
Website:”http://pacificrimmovie.com”,
Response:”True”
}
MovieModel
usingProject.Serializers;
usingNewtonsoft.Json;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.Threading.Tasks;
namespaceProject.Models
{
[DataContract] public
class Movie
{
publicMovie(){}
[DataMember]
publicintId{get;set;}
[DataMember]
publicstringImdbId{get;set;}
[DataMember]
publicstringTitle{get;set;}
[DataMember]
publicDateTimeReleased{get;set;}
[DataMember] [JsonConverter(typeof(RuntimeSerializer))]
publicTimeSpanRuntime{get;set;}
}
}
RuntimeSerializer
usingNewtonsoft.Json;
usingNewtonsoft.Json.Linq;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text.RegularExpressions;
usingSystem.Threading.Tasks;
namespaceProject.Serializers
{
publicclassRuntimeSerializer:JsonConverter
{
publicoverrideboolCanConvert(TypeobjectType)
{
returnobjectType==typeof(TimeSpan);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializerserializer)
{
if (reader.TokenType == JsonToken.Null) return null;
JTokenjt=JToken.Load(reader);
Stringvalue=jt.Value<String>();
Regexrx=newRegex(“(\\s*)min$”);
value=rx.Replace(value,(m)=>””);
inttimespanMin;
if(!Int32.TryParse(value,outtimespanMin))
{
thrownewNotSupportedException();
}
returnnewTimeSpan(0,timespanMin,0);
}
publicoverridevoidWriteJson(JsonWriterwriter,objectvalue,JsonSerializerserializer)
{
serializer.Serialize(writer,value);
}
}
}
CallingIt
Moviem=JsonConvert.DeserializeObject<Movie>(apiResponse));
Section83.2:CollectallfieldsofJSONobject
usingNewtonsoft.Json.Linq;usingSystem.
Collections.Generic;
publicclassJsonFieldsCollector
{
privatereadonlyDictionary<string,JValue>fields;
publicJsonFieldsCollector(JTokentoken)
{
fields=newDictionary<string,JValue>(); CollectFields(token);
}
privatevoidCollectFields(JTokenjToken)
{
switch(jToken.Type)
{
caseJTokenType.Object:
foreach(varchildinjToken.Children<JProperty>())
CollectFields(child);
break;
caseJTokenType.Array:
foreach(varchildinjToken.Children())
CollectFields(child);
break;
caseJTokenType.Property:
CollectFields(((JProperty)jToken).Value);
break;
default:
fields.Add(jToken.Path,(JValue)jToken); break;
}
}
publicIEnumerable<KeyValuePair<string,JValue>>GetAllFields()=>fields;
}
Usage:
varjson=JToken.Parse(/*JSONstring*/);
varfieldsCollector=newJsonFieldsCollector(json);
varfields=fieldsCollector.GetAllFields();
foreach(varfieldinfields)
Console.WriteLine($”{field.Key}:'{field.Value}'”);
Demo
ForthisJSONobject
{
“User”:”John”,
“Workdays”:{
“Monday”:true,
“Tuesday”:true,
“Friday”:false
},
“Age”:42
}
expectedoutputwillbe:
User: ‘John’
Workdays.Monday: ‘True’
Workdays.Tuesday:’True’
Workdays.Friday:’False’
Age: ’42’
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024