Receiving NodaTime.LocalTime - c#

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; }
}

Related

How to parse a complicated nested JSON string in C#?

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.

How to read JSON data?

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);
}

Passing date as string - prevent json.net from parsing date

I have a Web API middle layer which consumes an API which exposes a field which carries a timestamp as string (the field is string and it contains a value like "2016-05-31T14:12:45.753Z").
The proxy classes in the middle tier are generated using Visual Studio from Swagger endpoint and under the hood the object is deserialized using Json.NET.
I can see that the field was received as string (that's good):
inputObject {{ "When": "2016-05-31T14:12:45.753Z" }} Newtonsoft.Json.Linq.JToken {Newtonsoft.Json.Linq.JObject}
However, even though the target field is string the value of inputObject["When"] is a parsed as a timestamp.
inputObject["When"] {31/05/2016 14:12:45} Newtonsoft.Json.Linq.JToken {Newtonsoft.Json.Linq.JValue}
Then
JToken whenValue = inputObject["When"];
if (whenValue != null && whenValue.Type != JTokenType.Null)
{
this.When = ((string)whenValue);
}
In the end this.When is a string with value 31/05/2016 14:12:45.
Is there an option to prevent json.net from parsing the date and then casting it to string again?
Please remember that this transformation happens in auto generated code so I'm looking for some way of decorating the field on the server side which would make Swagger mark it somehow and then the generated classes would avoid the deserialize/serialize issue.
Something like:
[JsonProperty("This really is a string, leave it alone")]
public string When { get; private set; }
(Answering my own question)
I needed a solution quickly and this is my temporary solution, for the record.
I format the date as
"When": "2016-05-31 14:12:45"
and not
"When": "2016-05-31T14:12:45.753Z"
This prevents it from being interpreted. The front end (javascript) code knows that timestamps from the API are UTC and it appends 'Z' before transforming the timestamp to local time and formatting for display, e.g:
<td>{{vm.prettyDateTimeFormat(item.StatusDate+'Z')}}</td>
The ctrl code:
vm.prettyDateTimeFormat = function (dateString)
{
var momentDate = moment(dateString, "YYYY-MM-DD HH:mm:ssZZ");
if (typeof(momentDate) === "undefined" || (!momentDate.isValid()))
{
return dateString;
}
//The format needs to be sortable as it ends up in the grid.
var nicePrettyDate = momentDate.format('YYYY-MM-DD HH:mm:ss');
return nicePrettyDate;
}
As far as I don't like this solution it carried us through the demo. This issue is obviously in the back log now to be addressed properly.
[JsonIgnore]
public string When { get; private set; }

Parsing Facebook JSON Game Request Data

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.

JSON string failing in JSON.parse but passes JsonConvert.DeserializeObject

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"
}
}

Categories