Dynamic deserialize JSON from method - json

How to dynamic deserialize JSON from method in controller? I use that code:
dynamic dynJson = JsonConvert.DeserializeObject(GetReservedDaysJson().ToString());
And have that error:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: M. Path '', line 0, position 0.'
My JSON from GetReservedDaysJson() function look like that:
["2022-03-29","2022-03-30"]
Unless someone has a better solution. It needs to compare each date with JSON. With the date provided in the model.

you can try this
string json = GetReservedDaysJson();
List<DateTime> dates = JsonConvert.DeserializeObject<List<DateTime>>(json);

Related

JSON Object Parse

exercise question screenshot
Not sure what's missing. The other discussion solutions seem too complicated compared to my homework question:
Q:
-The variable str_json has been assigned a string of a JSON object
-Call the parse method, pass it str_json and assign the return value to variable jsonobj
-Assign the property the_city to the variable v_the_city
-Assign the property stateval to the variable v_stateval
var str_json = {'v_the_city':'the_city','v_stateval':'stateval'};
var jsonobj = JSON.parse(str_json);
SyntaxError:
the JSON dataJSON.parse: unexpected character at line 1 column 2 of
SyntaxError: unexpected token: identifier
str_json should be a JSON string, not an object.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. Read more here, link.
Syntax:
JSON.parse(text[, reviver])
Parameters:
text - The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver - [Optional] If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

Ruby parse string to json

So I have some json that looks like this, which I got after taking it out of some other json by doing response.body.to_json:
{\n \"access_token\": \"<some_access_token>\",\n \"token_type\": \"Bearer\",\n \"expires_in\": 3600,\n \"id_token\": \<some_token>\"\n}\n"
I want to pull out the access_token, so I do
to_return = {token: responseJson[:access_token]}
but this gives me a
TypeError: no implicit conversion of Symbol into Integer
Why? How do I get my access token out? Why are there random backslashes everywhere?
to_json doesn't parse JSON - it does the complete opposite: it turns a ruby object into a string containing the JSON representation of that object is.
It's not clear from your question what response.body is. It could be a string, or depending on your http library it might have already been parsed for you.
If the latter then
response.body["access_token"]
Will be your token, if the former then try
JSON.parse(response.body)["access_token"]
Use with double quotes when calling access_token. Like below:
to_return = {token: responseJson["access_token"]}
Or backslashes are escaped delimiters and make sure you first parse JSON.

Jettison can not convert json string to json object when there is an element has empty string value

My application is using camel rest (2.15.2) to catch a POST json String and then uses jettison to convert to a JSON Object. It is working fine with normal request.
POST request: {"request"={"lname"="aaa", "fname"="bb"}}
1. String body = exchange.getIn().getBody(String.class);
2. JSONObject obj = new JSONObject(body);
When i debug, variable body = {request={lname=aaa, fname=bb}}.
And line 2 returns a JSONObject. so far so good
if we try to another the request:
{"request"={"lname"=" ", "fname"="aa"}}
then body = {request={lname= , fname=aa}}
line2 returns Exception.
Could you please help me to fix this issue: convert json string which contains element has empty value string to json object.
The above request is acceptable in my scenarios.
Error:
org.codehaus.jettison.json.JSONException: Missing value. at character
15 of {request={lname= , fname=aa}} at
org.codehaus.jettison.json.JSONTokener.syntaxError(JSONTokener.java:463)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:356)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at
org.codehaus.jettison.json.JSONTokener.newJSONObject(JSONTokener.java:412)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:327)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:311)

Cannot parse MySql TImestamp with JSON

While trying to parse the following JSON string:
{
marketplaceId:"MKPL",
asin:"ASIN1",
sourceTimestamp:2013-03-19T23:38:24.054Z,
orderId:"ORD1",
vendorId:"SUPR1",
warehouseId:"SEA8",
inventoryOwnerGroup:376,
lastUpdatedAt:2013-03-19T23:38:23.919Z,
isHighConfidence:true,
quantityArriving:2,
expectedDeliveryDate:2013-03-19T23:38:23.919Z
}
I get the following exception:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.sql.Timestamp out of VALUE_EMBEDDED_OBJECT token
at [Source: N/A; line: -1, column: -1] (through reference chain: com.amazon.freshwombat.po.PurchaseRecord["lastUpdatedAt"])
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219)
at org.codehaus.jackson.map.deser.std.StdDeserializer._parseDate(StdDeserializer.java:580)
at org.codehaus.jackson.map.deser.std.TimestampDeserializer.deserialize(TimestampDeserializer.java:28)
at org.codehaus.jackson.map.deser.std.TimestampDeserializer.deserialize(TimestampDeserializer.java:19)
Am I missing something? Thanks!
JSON doesn't support the concept of "dates". It only supports simple data types like strings, numbers, arrays, booleans, etc. So, represent your dates as strings. E.g.:
lastUpdatedAt: "2013-03-19T23:38:23.919Z",
You'll have to do the actual date parsing with other JavaScript facilities/third-party libraries.
If you are using Jackson for JSon to Object conversion you must specify the DateFormat a mapper instance should use in order to generate Date from String values that represents a date or timestamp.
In the case of the of a (mysql) timestamp :
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(format)
Entity entity = mapper.readValue("{ }", Entity.class);
So closely following the advices of #SimpleCoder and with this snippet i guess you shouldn't have problems.

How to access json inputs

I am working in yii framework.I am having json input as-
$json='{"userId":1,"questionPaperId":1;"optionId":2}';
So whilw creating functions in yii,i am decoding it and accessing these inputs as-
$obj=CJSON::decode($json);
$option=$obj->optionId;
$userId=$obj->userId;
$paperId=$obj->questionPaperId;
But its giving error as "Trying to get property of non-object ". So how to access this in yii?
You json string is syntax wrong.
$json='{"userId":1,"questionPaperId":1;"optionId":2}'; // note the ; in it
should be
$json='{"userId":1,"questionPaperId":1,"optionId":2}';
As CJSON::encode give you a json formatted string from an array, CJSON::decode return an array not an object.
So access it like that: $option=$obj["optionId"];