When I try to send back a json string with the following json function the string is inserts new lines and escapes characters in vb.net.
Questions
- How do I get it to return as proper json?
- Is it possible to use something like Json(data:=jsonstr, JsonRequestBehavior.AllowGet) to fix the issue?
- Is it possible to use notation similar to C# when dealing with Json strings? Dim someJson as string= @"{""firstname"":"+c.c_firstname+"}"
-
Function get_people_jsonresult(Optional id As Integer = 0) As JsonResult
Dim c As dtb_people = db.dtb_people.Where(Function(x) x.c_Id = 1).Single
Dim jsonstr As String = "{
""firstname"":""" + c.c_firstname + """,
""lastname"":""" + c.c_lastname + """,
""id"":" + c.c_Id.ToString + "
}"
Return Json(jsonstr, JsonRequestBehavior.AllowGet)
End Function
Returned string
"[{\r\n \"firstname\":\"john\",\r\n \"lastname\":\"smith\",\r\n \"id\":1\r\n }]"
updated: The idea is to figure out different ways to do the same thing to figure out a style that I like.
1) I found this solution but kind of quirky but makes sense - i.e. turn it into an object it will recognize vs. something generic like Ctype(jsonstr, object). I think the point is that jsonresult is meant to serialize json, but this is already serialized, so it should be returned as is.
Dim d As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(jsonstr)
Return Json(d, JsonRequestBehavior.AllowGet)
2) Still not sure if something like this is possible
3) It doesn't look like @ offers any benefit since vb.net does multi-line string literals an optional format could be a string interpolation and to use single quotes vs. double so there is no need to escape them.
Dim jsonstr2 As String = $"{{
'firstname': '{c.c_firstname}',
'lastname':'{c.c_lastname}' ,
'id':{c.c_Id.ToString}
}}"
