I am currently using facebook and I have a callback method that returns a JSON result as a string.
The result has the following format:
{
"request": "420211088059698",
"to": [
"100002669403922",
"100000048490273"
]
}
How would I go about parsing the "to" into a list of some sort? This way I can use this list to verify that the user actually did indeed send a request to a friend to play the game.
Thanks guys
You can use JSON.Net for deserializing to a class of below structure:
Class Test{
public string request {get;set;}
public List<string> to {get;set;}
}
then just call deserialize method on the JSON string to get the object.
Test obj = JsonConvert.DeserializeObject<Test>(jsonstring);
You need to convert it to a class array. That can be done with Unity's built in JsonUtility API.
JsonUtility.ToJson to convert a class to Json.
JsonUtility.FromJson to convert Json back to class.
Visit here Json array example.
EDIT:
You asked for an example:
class FacebookInfo
{
public string request;
public string[] to;
}
void Start()
{
FacebookInfo fbInfo = new FacebookInfo();
string fbJson = "{\"request\": \"420211088059698\",\"to\": [\"100002669403922\",\"100000048490273\"]}";
fbInfo = JsonUtility.FromJson<FacebookInfo>(fbJson);
//Show request
Debug.Log("Request: " + fbInfo.request);
//Show to arrays
for (int i = 0; i < fbInfo.to.Length; i++)
{
Debug.Log("To : " + fbInfo.to[i]);
}
}
Tested with Unity 5.4.0.13B and it looks like Unity now support Json array without writing extra code. Just make sure you have this version I mentioned.
just use SimpleJson http://wiki.unity3d.com/index.php/SimpleJSON , no extra work needed , look at the example , all you need to do is use JSON.Parse and you an array and can use it like data["request"] to get the values, hope this helps.
Related
I keep getting the error Cannot convert value to NodaTime.LocalTime, and I can't seem to find anyone else with the problem. I also can't find in the documentation how I can do this.
An example of what I'm trying to send is;
{
"time": "22:00"
}
Is something wrong with this format? As far as I'm aware, NodaTime.LocalTime is formatted exactly like this. I know a similar problem exists for the date object, but it really doesn't apply to this, as it has no Z at the end of the string. I also tried taking the semi-colon out of the string I send, but that didn't do anything.
Thank you!
your json is invalid, pls fix it according this example
using NodaTime.Serialization.JsonNet;
var d = new Data { time = NodaTime.LocalTime.Noon };
var json = JsonConvert.SerializeObject(d);
output
{"time":"12:00:00"}
So your json should be
var json = #"{
""time"": ""22:00:00""
}";
Data data = JsonConvert.DeserializeObject<Data>(json);
everything is working properly in this case
class
public class Data
{
public LocalTime time { get; set; }
}
I have an ugly JSON string that is getting returned from an API that looks like this (this is the result of Console.Write on the string):
{"d":"\"\\\"\\\\\\\"[{\\\\\\\\\\\\\\\"foo\\\\\\\\\\\\\\\":15,\\\\\\\\\\\\\\\"bar\\\\\\\\\\\\\\\":null}]\\\\\\\"\\\"\\n\""}
I am trying to parse this into a C# object in the simplest way possible, so I can access properties like foo and bar. But I am having a difficult time doing this.
I have tried parsing it a number of ways, including:
// code to get the response string
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var serializedData = "{data: 'data'}";
var responseString = client.UploadString(url, "POST", serializedData);
// parse the response string
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
This allows me to access the value of d, which is the actual string I need to parse. I then tried to parse that separately using JArray.Parse(obj["d"]), but I get an error saying that obj["d"] is not an array.
Unfortunately, I have no access to the API itself so can't modify how it's serializing the data it's returning.
Any suggestions?
You can replace all New Line, Backslash, Double quotes to format the JSON
var formattedJson = jsonString.Replace(#"\n", string.Empty)
.Replace(#"\", string.Empty)
.Replace("\"\"", string.Empty);
Console.WriteLine(formattedJson);
OUTPUT
{
"d": [
{
"foo": 15,
"bar": null
}
]
}
Convert to JArray.
var jArray = JArray.Parse(JObject.Parse(formattedJson)["d"].ToString());
Console.WriteLine($"{jArray[0]["foo"]} {jArray[0]["bar"]}");
OUTPUT
15
The problem is that the value of "d" is a string representing a string representing a string ... representing an array. You could call it JSON serialization "inception".
The way to deal with this is to deserialize the value corresponding number of times. If you're sure that the value is never going to be an actual string, you could do it like this, without having to know how many times the value was serialized:
var myObject = JObject.Parse(s);
var d = myObject["d"];
while(d.Type == JTokenType.String)
d = JToken.Parse(d.ToObject<string>());
myObject["d"] = d;
After this procedure myObject represents this data:
{
"d": [
{
"foo": 15,
"bar": null
}
]
}
Replacing escape characters in fine however I would not rely on the console.write command as the definitive output to examine. Here are a couple of other ways: -
Use Postman to make the API call so you can see the raw result. This will (hopefully) show it in an easy to read format that you can then define your class to deserialise to.
Write the raw response to a “.json” file. Open that file in a good editor (such as VS Code or VS itself) to see how the data is actually structured when it is received.
On a side note I would recommend using RestSharp to do the REST calls and Newtonsoft.Json to do the serialising/deserialising.
Is this json data format?
string json = {"answer":"Line 1","mark": 1},{"answer":"Line 3","mark": 1}
I try below code but it only working with one param. ex: {"answer":"Line 1","mark": 1}. I try split json string but it isn't best way.
JObject jObject = JObject.Parse(json );
string asw = jObject["answer"].ToString();
int mark = (int)jObject["mark"];
txtAnswer.Text = asw + "////" + mark + "\n";
This is a very basic JSON question which any number of tutorials could've answered for you.
Is it valid JSON ? No, and JSONLint could've told you that.
How do you read it in ?
First, wrap your JSON in square brackets so it's valid.
Then, define a class to store the records in:
public class Something
{
public string answer { get; set; }
public string mark { get; set; }
}
And finally, use JSON.Net to convert your string into a list of these records.
string json = "[{\"answer\":\"Line 1\",\"mark\": 1},{\"answer\":\"Line 3\",\"mark\": 1}]";
List<Something> records = JsonConvert.DeserializeObject<List<Something>>(json); // JSON.Net
foreach (Something record in records)
{
System.Diagnostics.Trace.WriteLine(string.Format("Answer: {0}, Mark: {1}", record.answer, record.mark));
}
Easy as that.
Is this json data format?
string json = {"answer":"Line 1","mark": 1},{"answer":"Line 3","mark": 1}
Nope, what you've got there doesn't look like valid C# or JSON. Try putting it inside a JSON array, then inside a proper string:
string json = "[{\"answer\":\"Line 1\",\"mark\": 1},{\"answer\":\"Line 3\",\"mark\": 1}]";
(Hope I've got all the escaping right there.)
That's the C# escaped equivalent of the following JSON:
[{"answer":"Line 1","mark": 1}, {"answer":"Line 3","mark": 1}]
Then read up on JObject.Parse()for more info.
Yes it is json format. But There are multiple objects. You are not looping through it. One way could be
dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
Console.WriteLine("{0} {1}\n", item.answer, item.mark);
}
My C# class is
public class Man
{
public string name {get; set;}
}
String to deserialize is like this
var content = "[{name: \"john\"}]"
Now before saving to db, I was doing check that if string can be deserialized to C# object then store it. This check passes
JsonConvert.DeserializeObject<List<Man>>(content)
So I save this string in db but when I do JSON.parse over saved string in javascript, it crashes with error
JSON.parse("[{name: \"john\"}]")
SyntaxError: Unexpected token n
Now I understand that by surrounding quotes around key ("name") this can be solved. This is correct string that works in both JSON.parse and JsonConvert.DeserializeObject
var content = "[{\"name\": \"john\"}]
Problem is I have many such ill formed strings in db already that crash on JSON.parse only. What is the best way to convert such strings so that JSON.parse will work? Something better than string.replace
Please note that actual strings are quite big and complicated compared to example given.
You can use the using Newtonsoft.Json; it will DeserializeObject object even your json data in var content = "[{name: \"john\"}]" format.
value contains data like :{StyleId:"1710","SelectedItemToColorMap":{1391:"583",21531:"7733"}}
var jsondata = JsonConvert.DeserializeObject(value);
after DeserializeObject the jsondata look like
{
"StyleId": "1710",
"SelectedItemToColorMap": {
"1391": "583",
"21531": "7733"
}
}
I want to directly capture JSON from an external API in a service layer, return that to a MVC 4 ApiController, and then output the JSON through that ApiController. I'm basically writing a wrapper around another API service because some other actions have to happen at the same time (authentication, etc). The problem is that the JSON gets converted to a string and is passed around as a string in my C# code. This just adds escape characters to the JSON. Is there anyway I can just pass the JSON object around in my C# code? Details of my implementation are below.
In a service layer, I'm consuming an API that provides JSON via the method below.
return new WebClient().DownloadString(url);
Unfortunately this returns a string. As this API is already returning JSON to me this is problematic because lots of escape characters get added to the string.
The JSON should look something like this
[{"Citation":{"Attachments":[{"AttachedPersonIds":null,..."Type":"Record"}]
But instead it now looks like this
"[{\"Citation\":{\"Attachments\":[{\"AttachedPersonIds\":null,...\"Type\":\"Record\"}]"
After I get this string I return it through a couple of methods to an ApiController (which is setup to return JSON) like this.
public class HintsController : ApiController
{
public string Get(string treeId, string personId)
{
return _hintService.GetHints(treeId, personId);
}
}
I've tried to convert the string to a Literal string and tried serializing the string again. Doing this just adds more escape characters and doesn't solve the problem. I think the problem is with how I'm consuming the initial call because it's casting it from JSON to a string. But I don't know how to avoid this.
Thanks in advance for any ideas.
Because the controller returns a string, the JSON formatter is serializing the entire string to a JSON string and escaping the embedded quote characters.
You can do something like this:
public HttpResponseMessage Get()
{
var resp = new HttpResponseMessage()
{
Content = new StringContent("{json here...}")
};
resp.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
return resp;
}
This assumes that you always want to return JSON.
You can turn it into a dynamic object and pass that around, if you really want to pass the objects.
I can't tell where the literal escape characters are coming from, can you be a little more clear on that. Is the API generating them, or is there some other point in our code? I've seen them in the debug window before, when the string didn't actually contain them, and printing/etc worked normally.
You can use Json.net (standard), the built in serializer, https://github.com/jsonfx/jsonfx and others .
From the jsonfx site:
var reader = new JsonReader(); var writer = new JsonWriter();
string input = #"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }";
dynamic output = reader.Read(input);
Console.WriteLine(output.array[0]); // 42
string json = writer.Write(output);
Console.WriteLine(json); // {"foo":true,"array":[42,false,"Hello!",null]}
There are a few other ways ways, see these threads:
Deserialize json object into dynamic object using Json.net
Deserialize JSON into C# dynamic object?