So i have some Json:
{
"name": "Shadow Realm",
"description": "A spooky Haloween inspired map",
"map": {
"version": 79,
"color_palette": [
{
"r": 96,
"g": 209,
"b": 234,
"a": 255
},
{
"r": 255,
"g": 55,
"b": 55,
"a": 255
}]
}
}
And i am am able to read the first few values however i am not able to read the version and i am not sure what i should be reading the map entry as, any ideas?
I would prefer not to have to use a plugin as i wish to keep the project as small as possible if its do-able.
using UnityEngine;
using System.Collections;
using System.Reflection;
using System.Linq;
using System;
[System.Serializable]
public class Tests : MonoBehaviour
{
private string jsonMapData;
void Start()
{
jsonMapData = Import_bnl_bin.LoadResourceTextfile("map.json");
MyClass jsonMap = new MyClass();
jsonMap = JsonUtility.FromJson<MyClass>(jsonMapData);
Debug.Log("Name " + jsonMap.name + " : Desc " + jsonMap.description + " : Version " + jsonMap.version);
}
public class MyClass
{
public string name;
public string description;
public int version;
}
}
Use http://json2csharp.com I generated the following classes using your sample JSON document.
public class ColorPalette
{
public int r { get; set; }
public int g { get; set; }
public int b { get; set; }
public int a { get; set; }
}
public class Map
{
public int version { get; set; }
public List<ColorPalette> color_palette { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string description { get; set; }
public Map map { get; set; }
}
I'm not familiar with JsonUtility but my guess would be that you would replace this line:
jsonMap = JsonUtility.FromJson<MyClass>(jsonMapData);
With this:
jsonMap = JsonUtility.FromJson<RootObject>(jsonMapData);
Or you could rename RootObject to MyClass.
it seems that the classes needed to be serializable
[Serializable]
public class Map
{
public int version;
public List<ColorPalette> color_palette;
}
otherwise it fails to read the data, also i ended up removing the
{ get; set; }
as it was overriding the
.FromJson()
funtion and causing it to return null
Related
Good day, I just can't seem to wrap on this, I have this JSON document in mind, but how can I do it as a class?
the JSON goes like this :
{
"name": "stacking",
"id": "12345",
"moreDetails" : {
"new_item_0" : {
"id": "abcdefg"
},
"new_item_1" : {
"id": "hujklmn"
},
"new_item_n" : {
"id": "opqrtsu"
}
}
}
Where "moreDetails" have an infinite amount of "new_item_n" in it.
Gonna use this class as a format of my database in MongoDB.
The class I have in mind goes like this:
public string name;
public string id;
// beyond here I have no idea
You can use Dictionary<string, class>:
public partial class Root
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("moreDetails")]
public Dictionary<string, Item> MoreDetails { get; set; }
}
public class Item
{
[JsonProperty("id")]
public string Id { get; set; }
}
So this:
var x = new Root
{
Name = "stacking",
Id = "1",
MoreDetails = new Dictionary<string, Item> {
{"new_item_0", new Item {Id = "itemId"}}
}
};
JsonConvert.SerializeObject(x, Newtonsoft.Json.Formatting.Indented);
results in:
{
"name": "stacking",
"id": "1",
"moreDetails": {
"new_item_0": {
"id": "itemId"
}
}
}
Try using KeyValuePair where ObjectType is the class that describes the object behind your new_item_n
List<KeyValuePair<string,ObjectType>>
Or use the dictionary as the answer of Guru Strom!
Well since MovieDetails will be an infinite and dynamic it should be a dictionary. So something like this:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace Scratch
{
class Program
{
class Thing
{
public string Name { get; set; }
public string Id { get; set; }
public Dictionary<string, Item> MoreDetails { get; set; }
}
class Item
{
public string Id { get; set; }
}
static void Main(string[] args)
{
var json = File.ReadAllText("f.json");
var thing = JsonConvert.DeserializeObject<Thing>(json);
Console.WriteLine(thing.Name);
}
}
}
This class I created myself:
public class member
{
public string account_name { get; set; }
public long account_id { get; set; }
public Rootobject[] rootobject { get; set; }
}
This are the classes VS created for me autmatically using an example JSON answer:
public class Rootobject
{
public string status { get; set; }
public Meta meta { get; set; }
public Data data { get; set; }
}
public class Meta
{
public int count { get; set; }
}
public class Data
{
public _507888780[] _507888780 { get; set; }
}
public class _507888780
{
public All all { get; set; }
public int tank_id { get; set; }
}
public class All
{
public int spotted { get; set; }
public int hits_percents { get; set; }
public int wins { get; set; }
...
}
A small part of the JSON response from the API server I use looks like this:
{
"status": "ok",
"meta": {
"count": 1
},
"data": {
"507888780": [
{
"all": {
"spotted": 467,
"hits_percents": 83,
"wins": 281,
},
"tank_id": 2849
},
{
"all": {
"spotted": 224,
"hits_percents": 63,
"wins": 32,
},
"tank_id": 9473
},
}
}
This is the code I use to read out the tanks a member has (including all the stats) where Request(string) is just the http request.
private List<member> memberlist = new List<member>(100);
private void DoStuff()
{
memberlist = JsonConvert.DeserializeObject<List<member>>(result_member);
foreach (var member in memberlist)
{
string result_tank = Request("https://api.worldoftanks.eu/wot/tanks/stats/?application_id=" + application_id + "&account_id=" + member.account_id + "&tank_id=" + tanks + "&fields=all.battles%2C+all.wins%2C+all.damage_dealt%2C+all.frags%2C+all.hits_percents%2C+all.piercings%2C+all.shots%2C+all.spotted%2C+all.survived_battles%2C+all.tanking_factor");
var Rootobject = JsonConvert.DeserializeObject<Rootobject>(result_tank);
foreach (var tank in _507888780)
{
richTextBox1.Text += Rootobject.data._507888780[tank].tank_id + Rootobject.data._507888780[tank].all.spotted.ToString() + "...";
}
}
}
Now, I want to be able to search up all the different tanks including their stats for all members. Right now I'm getting the error in the line I want to print "Type Tank_Statistics._507888780 cannot be implicitly converted to int." Earlier on I alos got an error with a missing IEnumerable which I dont have right now though..
Anyways .. I can't make it work somehow.. it would be very kind if someone would be able to help me on this ;)
Seems that you should replace this
richTextBox1.Text += Rootobject.data._507888780[tank].tank_id + Rootobject.data._507888780[tank].all.spotted.ToString() + "...";
to this
richTextBox1.Text += tank.tank_id + tank.all.spotted.ToString() + "...";
I have a Json File like this.
{
"_request": {
"api_ver": 1,
"route": "/api/v2/u/SunDwarf-21353/stats/general"
},
"average_stats": {
"damage_done_avg": 3987.0,
"deaths_avg": 5.68,
"defensive_assists_avg": 0.0,
"eliminations_avg": 10.47,
"final_blows_avg": 6.12,
"healing_done_avg": 589.0,
"melee_final_blows_avg": 0.03,
"objective_kills_avg": 3.06,
"objective_time_avg": 0.007222222222222223,
"offensive_assists_avg": 0.0,
"solo_kills_avg": 2.3,
"time_spent_on_fire_avg": 0.008055555555555555
},
"battletag": "SunDwarf-21353",
"game_stats": {
"cards": 36.0,
"damage_done": 478462.0,
"damage_done_most_in_game": 13303.0,
"deaths": 682.0,
"defensive_assists": 39.0,
"defensive_assists_most_in_game": 11.0,
"eliminations": 1257.0,
"eliminations_most_in_game": 26.0,
"environmental_deaths": 12.0,
"environmental_kills": 8.0,
"final_blows": 735.0,
"final_blows_most_in_game": 16.0,
"games_played": 120.0,
"games_won": 59.0,
"healing_done": 70670.0,
"healing_done_most_in_game": 7832.0,
"kpd": 1.84,
"medals": 304.0,
"medals_bronze": 102.0,
"medals_gold": 100.0,
"medals_silver": 102.0,
"melee_final_blows": 4.0,
"melee_final_blows_most_in_game": 2.0,
"multikill_best": 3.0,
"multikills": 5.0,
"objective_kills": 368.0,
"objective_kills_most_in_game": 10.0,
"objective_time": 0.8880555555555555,
"objective_time_most_in_game": 0.026944444444444444,
"offensive_assists": 13.0,
"offensive_assists_most_in_game": 7.0,
"recon_assists": 9.0,
"solo_kills": 277.0,
"solo_kills_most_in_game": 16.0,
"time_played": 15.0,
"time_spent_on_fire": 0.9961111111111111,
"time_spent_on_fire_most_in_game": 0.08833333333333333
},
"overall_stats": {
"avatar": "https://blzgdapipro-a.akamaihd.net/game/unlocks/0x02500000000008E8.png",
"comprank": null,
"games": 120,
"level": 24,
"losses": 61,
"prestige": 0,
"win_rate": 49,
"wins": 59
},
"region": "eu"
}
So I want to Deserialie this in C# . so I create with json2csharp.com the Classes.
Now its possible to instantiate all these classes, but this is bad I don't need a instance of GameStats, or average_stats.
What's my line here, how I can make this class not creatable?
sorry for my english, hope you can follow my problem :D
best regards. alex
Simply remove unwanted properties form RootObject
public class RootObject
{
public Request _request { get; set; }
//public AverageStats average_stats { get; set; }
public string battletag { get; set; }
//public GameStats game_stats { get; set; }
public OverallStats overall_stats { get; set; }
public string region { get; set; }
}
Deserializer omits them.
So you mean you don't know how to use a deserializer?
Take a look at this link
Simply do it like this:
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
// james#example.com
Make your classes nested to stop classes being shown in intellisense and add parameterless private constructors. Don't worry about private constructors, Json.NET uses reflection to instantiate your classes.
public class RootObject
{
public class GameStats
{
private GameStats() { }
//Code omitted
}
public class Request
{
private Request() { }
//Code omitted
}
public class AverageStats
{
private AverageStats() { }
//Code omitted
}
public class OverallStats
{
private OverallStats() { }
//Code omitted
}
public Request _request { get; set; }
public AverageStats average_stats { get; set; }
public string battletag { get; set; }
public GameStats game_stats { get; set; }
public OverallStats overall_stats { get; set; }
public string region { get; set; }
}
Compiler gives error:
//'RootObject.GameStats.GameStats()' is inaccessible due to its protection level
var myClass = new RootObject.GameStats();
I'm attempting to parse a rather convoluted/unnecessarily complicated JSON output using newtonsoft in C# however for some reason my parser always returns null and doesn't elaborate as to exactly why this is the case.
An example of a JSON file I'm trying to parse:
{
"response": {
"success": 1,
"current_time": 1362339098,
"prices": {
"35": {
"11": {
"0": {
"current": {
"currency": "keys",
"value": 39,
"value_high": 41,
"date": 1357515306
},
"previous": {
"currency": "keys",
"value": 37,
"value_high": 39
}
}
},
"3": {
"0": {
"current": {
"currency": "metal",
"value": 0.33,
"value_high": 0.66
}
}
}
},
"5002": {
"6": {
"0": {
"current": {
"currency": "usd",
"value": 0.39,
"value_high": 0.42,
"date": 1358090106
}
}
}
},
"5022": {
"6": {
"1": {
"current": {
"currency": "metal",
"value": 1.33,
"value_high": 1.55,
"date": 1357515175
}
}
}
}
}
}
}
And the C# parser I'm using. I run the getCurrentPrices() to return a PriceParser object but instead the object returned is always null.
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using System.Diagnostics;
namespace SteamBot
{
class PriceParser
{
//Methods
public PriceParser updatePrices()
{
var json = File.ReadAllText("test.json");
ParserResult result = JsonConvert.DeserializeObject<ParserResult>(json);
return result.result;
}
public Data currentPrices { get; set; }
//DATA
public class Data
{
public Response Response { get; set; }
}
public class Response
{
public string success { get; set; }
public string current_time {get; set;}
public List<Price> prices { get; set;}
}
public class Price
{
public int defindex { get; set; }
public int quality { get; set; }
public Current current { get; set; }
public Previous previous { get; set; }
}
public class Current
{
public string currency { get; set; }
public float value { get; set; }
public float value_high { get; set; }
public int date { get; set; }
}
public class Previous
{
public string currency { get; set; }
public float value { get; set; }
public float value_high { get; set; }
public int date { get; set; }
}
protected class ParserResult
{
public PriceParser result { get; set; }
}
}
}
I'm probably just missing something stupid but for the life of me I can't figure out what, anyone with more JSON wrangling experience know what's going on here?
You are getting null values because your class structure does not match your JSON.
The first issue is that you are deserializing into a ParserResult when you should be using a Data. Data has a response property, matching your JSON. ParserResult does not have this property.
The second issue is that you have defined prices to be a List<Price>, but your JSON does not contain an array. Instead, the JSON structure is actually a series of nested dictionaries.
Try defining your inner classes like this:
public class Data
{
public Response response { get; set; }
}
public class Response
{
public int success { get; set; }
public long current_time { get; set; }
public IDictionary<int, IDictionary<int, IDictionary<int, Price>>> prices { get; set; }
}
public class Price
{
public Quote current { get; set; }
public Quote previous { get; set; }
}
public class Quote
{
public string currency { get; set; }
public decimal value { get; set; }
public decimal value_high { get; set; }
public long date { get; set; }
}
Then, in your updatePrices method you can deserialize like this:
public PriceParser updatePrices()
{
var json = File.ReadAllText("test.json");
currentPrices = JsonConvert.DeserializeObject<Data>(json);
return this;
}
Here is how you would dump out the data:
PriceParser parser = new PriceParser();
parser.updatePrices();
foreach (var defindex in parser.currentPrices.response.prices)
{
Console.WriteLine("defindex: " + defindex.Key);
foreach (var quality in defindex.Value)
{
Console.WriteLine("\t quality: " + quality.Key);
foreach (var price in quality.Value)
{
Console.WriteLine("\t\t index: " + price.Key);
Console.WriteLine("\t\t\t current price:");
Console.WriteLine("\t\t\t\t currency: " + price.Value.current.currency);
Console.WriteLine("\t\t\t\t value: " + price.Value.current.value);
Console.WriteLine("\t\t\t\t value_high: " + price.Value.current.value_high);
if (price.Value.previous != null)
{
Console.WriteLine();
Console.WriteLine("\t\t\t previous price:");
Console.WriteLine("\t\t\t\t currency: " + price.Value.previous.currency);
Console.WriteLine("\t\t\t\t value: " + price.Value.previous.value);
Console.WriteLine("\t\t\t\t value_high: " + price.Value.previous.value_high);
}
}
}
}
And here is the output of the above:
defindex: 35
quality: 3
index: 0
current price:
currency: metal
value: 0.33
value_high: 0.66
quality: 11
index: 0
current price:
currency: keys
value: 39
value_high: 41
previous price:
currency: keys
value: 37
value_high: 39
defindex: 5002
quality: 6
index: 0
current price:
currency: usd
value: 0.39
value_high: 0.42
defindex: 5022
quality: 6
index: 1
current price:
currency: metal
value: 1.33
value_high: 1.55
I am trying to Deserialize a JSON api to c# on WP7. I need help in doing so. Im sure its an easy fix but i cannot just see it.
The JSON Data looks like this.
{
"chartDate" : 1349564400,
"retrieved" : 1349816722,
"entries" :
[
{
"position" : 1,
"previousPosition" : 0,
"noWeeks" : 1,
"artist" : "Rihanna",
"title" : "Diamonds",
"change" :
{
"direction" : "none",
"amount" : 0,
"actual" : 0
}
},
which translates to the following using http://json2csharp.com/
public class Change
{
public string direction { get; set; }
public int amount { get; set; }
public int actual { get; set; }
}
public class Entry
{
public int position { get; set; }
public int previousPosition { get; set; }
public int noWeeks { get; set; }
public string artist { get; set; }
public string title { get; set; }
public Change change { get; set; }
}
public class RootObject
{
public int chartDate { get; set; }
public int retrieved { get; set; }
public List<Entry> entries { get; set; }
}
In the application when i click the get feed button i am using the following code but it is coming back with the error Cannot Deserilize JSON object into type "System.Collections.Generic.List`1[Appname.RootObject
The following is my C# from Mainpage.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Reactive;
using Newtonsoft.Json;
namespace JsonDemo
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void Load_Click(object sender, RoutedEventArgs e)
{
var w = new SharpGIS.GZipWebClient();
Observable.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized = JsonConvert.DeserializeObject<List<RootObject>>(r.EventArgs.Result);
PhoneList.ItemsSource = deserialized;
});
w.DownloadStringAsync(new Uri("http://apiurl.co.uk/labs/json/"));
}
}
}
if r.EventArgs.Result returns the (correct) json in question, this should work:
var deserialized = JsonConvert.DeserializeObject<RootObject>(r.EventArgs.Result);
--EDIT--
string json = #"{
""chartDate"": 1349564400,
""retrieved"": 1349816722,
""entries"": [{
""position"": 1,
""previousPosition"": 0,
""noWeeks"": 1,
""artist"": ""Rihanna"",
""title"": ""Diamonds"",
""change"": {
""direction"": ""none"",
""amount"": 0,
""actual"": 0
}
}]
}";
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);