I have a json returned from the Facebook SDK in unity that looks like this:
{"name":"Name_of_person", "id":"989988988"}
I've taken a look at the raw JSON and this is what it looks like after I submit a query for that information via the Graph API.
So far I am trying to deserialize the json as such:
void DealWithProfileInfo(IGraphResult result){
Dictionary<string,string> profile = JSON.Deserialize (result.RawResult) as Dictionary<string,string>;
scoresText.text = profile ["first_name"];
idText.text = profile["id"];
DealWithProfileInfo being my callback method from the FB.API call.
for some reason none of the information gets displayed and I am not sure why.
Am I missing something? Or maybe I am parsing the data wrong?
Actually it is my personal experience that whenever I mess up with Facebook SDK or any other JSON in Unity3d, then what ever the hierarchy of JSON would be, it always returns Dictionary<string,object>. So developer have to come through that stairs
So in your case you should declare and cast to Dictionary<string,object> instead of Dictionary<string,string> then convert that object to string.
Related
Noob junior dev here trying to fix some old code written by someone else more senior but left. This person had a json file with a structure like this:
A: {
B: {
C: stuff1,
D: stuff2,
E: stuff3
}
},
...
The old code deserializes the json file into a JObject then tries to get information from the child node like this:
stuff1 = jObject["C"];
When I run the code, it just fills stuff1 with null. When I use the whole path like this:
stuff1 = jObject["A"]["B"]["C"]
I get the information I need from the child node. Just wondering if this was an oversight on the original author's part or if there's something I'm not seeing.
Am I right that you shouldn't be able to access the information in the child node without navigating through the tree properly? Is there any more robust way to get the information from the child node directly? I can see a scenario where if the structure of the Json file changes, then the jObject["A"]["B"]["C"] will no longer work.
If you're using Json.NET it looks like a bug or json changed.
However you address the situation write a unit test that shows what json(s) the code is expected to work with. The next dev will be have it easier; and that next dev may be you in 6 months.
Dealing with changing json
I can see a scenario where if the structure of the Json file changes, then the jObject["A"]["B"]["C"] will no longer work.
Dealing with changing json is ... let's say hard. If the json libary you're using supports JSONPath you could try with '$..C'. If you're using Json.NET have a look at Querying JSON with LINQ.
Fixing the bug
Use jObject["A"]["B"]["C"] or deserialise to a class and move on.
I am currently trying to save a list in Xamarin forms. I use this code snippet:
var list = new List<myClass> ();
Application.Current.Properties["myList"] = list;
await Application.Current.SavePropertiesAsync();
When I then close the app and use this code...
if (Application.Current.Properties.ContainsKey("myList"))
{
}
...I cannot reach this if statement.
I read something about people having issues saving a list with this solution but they solved it by converting it to a string. I am a bit unsure on how to do this. If I do this...
Application.Current.Properties["myList"] = list.ToString();
...the app crashes.
I saw that there is a plugin called "Settings" that I might need to use instead in case there isn't a solution to this problem but I would prefer to work with my current code if possible.
The Properties dictionary can only serialize primitive types for
storage. Attempting to store other types (such as List can
fail silently).
It means that you can't save List because it's not a primitive type of object. You can serialize it to JSON string for example then it will work. Code example:
var jsonValueToSave = JsonConvert.SerializeObject(myList);
Application.Current.Properties["myList"] = jsonValueToSave;
await Application.Current.SavePropertiesAsync();
Don't forget to deserialize JSON to List<string> when loading the value back.
Note that yourList.ToString() will not work in this case. More info here.
P.S.: Get familiar with the official documentation & check this post on another related thread.
Here's my situation: I have an MVC3 app that has some very complex C# objects, and those get rendered to a views in this application. However, I have a new requirement: a console application (that I am also writing) will run under a scheduler, and it needs to pull these objects from this MVC3 app, and then do something else with these complex objects.
Since I have control over both apps, I can share a library of the complex objects between them. All of these objects are marked [Serializable]. However, I cannot figure out an easy way to serialize these objects and send them from the MVC3 app to the Console app.
I tried simple JavaScriptSerializer and using the HttpClient to read the string, then deserialize it on the console-app end of things, but unfortunately it doesn't deserialize the data correctly. Everything is null. I can inspect the string on a breakpoint when it arrives at the console app, and all the data is there, in the string, but it just doesn't get de-serialized correctly.
Is there an easier way to do this? I don't care what the serialization method is. The data doesn't have to be passed as JSON and no other application but mine is going to consume these objects. But so far I can't figure out the easiest way to produce/consume these objects.
I know I can go down the whole "create a web service contract" and use data annotations route, but I was hoping there was an easier, less time-consuming way of doing it.
Using Json.NET:
Server-Side
string serializedObject = JsonConvert.SerializeObject(yourComplexObject);
// Send the string to the client...
Client-Side
In the client, you don't even have to know the deserialized object's type, you can take advantage of anonymous objects and dynamic:
string serializedObject = // ... Fetch from server
dynamic complexObject = JsonConvert.DeserializeObject(serializedObject);
// ...
string id = complexObject.UserId;
P.S.: Please note that the object's methods or state is not going to get serialized, only the public properties are.
Can your action just return your object? If so, your client code would look something like (using HttpClient)
var result = client.GetAsync(url).Result;
var myObj = await result.Content.ReadAsAsync<T>();
Hi I'm quite new to C# and I'm trying to make a text editor that saves and loads Plaintext formats. I've used NewtonSoft.Json NuGet package, but I'm getting an error. I've stated a string called textToLoad, which is set to a JsonConvert.DeserializeObject. Only thing is, it says it can't convert an object to a string! I tried toString(); but it still had the same error.
It is kind of hard without the code. The process of serializing and deserializing is pretty straight forward using Json.Net. So this is an example from their documentation:
YourType yourObject= new YourType();
yourObject.Property="something";
string output = JsonConvert.SerializeObject(yourObject);
//For some reason you want this to be string, but is the type you serialized in the first place
YourType textToLoad= JsonConvert.DeserializeObject<YourType>(output);
This outlines the basic works of serializing and deserializing. But we don't really know the details of your implementation.
Hope it helps.
You can't deserialize into a string like that. At simplest form you started with JSON in the form of:
{ value: "someString" }
If you want something out of it, you must deserialize and then get the value from it.
dynamic foo = JsonConvert.DeserializeObject<dynamic>(theJson);
var textToLoad = foo.value.ToString();
You must deserialize to something in order to inspect and get properties from it.
[Edit] - Perhaps I'm not understanding. But if you share code, I'll update my answer.
Can I use JSON to send a complex object from one pc to another?
From my understanding of JSON you can just stringy that object, then send the string to the other pc and then destringify it and rebuild the object again.
But now how does it know what object I have sent it? cause I could send it object A or object B ?
Is there a way to find out what object I have sent it? Or is part of JSON knowing what type of object you are going to receive?
Can I use JSON to send a complex object from one pc to another?
Yes
But now how does it know what object I have sent it? cause I could
send it object A or object B ?
The receiver knows when it deserialises the Json. The receiver needs to know what the Json will look like or dynamically deserialise it if it cannot know. See this SO answer on dynamically deserialising.
dynamic something = JsonConvert.DeserializeObject(json);
If as client you use as an instance of a class like Spring RestTemplate, you can tell it which class it should expect the JSon to be an instance of, and convert it accordingly.
http://www.springframework.net/rest/doc-latest/reference/html/resttemplate.html
JSON is the string representation of data.
You either know what the other side expects or need to send additional meta-data.
Very often you know exactly what kind of object has been sent.
Adding additional meta-data could easily be done automatically (and I am sure there are a lot of libraries available):
{
class: A
entity: {...}
}
But now how does it know what object I have sent it? cause I could
send it object A or object B ?
The other side should be aware to the fact that a JSON object has been received in a string format and accordingly, to parse or deserialize it properly, just like in the following example, which takes a JSON string and parse it to JSON or C# object:
In JavaScript:
var jsonObj = JSON.parse(yourJsonString);
In C#:
dynamic jsonObj = JsonConvert.DeserializeObject(yourJsonString);
In addition, if it's an HTTP request, you can specify the content-type to: application/json.
This way, the receiver side could analyze it and understand it is a JSON string.
Read more:
JSON.parse()
JavaScriptSerializer.DeserializeObject Method