Deserializing a JSON into a JavaScript object
Modern browsers support JSON.parse()
.
var arr_from_json = JSON.parse( json_string );
In browsers that don't, you can include the json2
library.
deserialize json object in javascript
Since you specified dataType: "json"
in your ajax options, jQuery will already have done the deserialising of the JSON string back into a JavaScript object for you automatically.
What you're seeing is just what alert()
does with JavaScript objects/arrays by default when trying to make them visual as text.
Try
alert(JSON.stringify(response));
instead. This will print a version of your object which is serialised back to a JSON string and thus make it more human-readable.
Or you can just look in the Response section of the ajax call's entry in your Network tab (in the browser's Developer Tools).
Also if you're using a JsonResult (i.e. return Json...
) you do not need to serialise the object beforehand - MVC will do it for you. So chances are you're getting double-serialised nonsense.
Simply
return Json(listt, JsonRequestBehavior.AllowGet);
should work no problem.
deserialize JSON to JAVASCRIPT object
You could create a function that initializes those objects for you. Here's one I quickly drafted:
function parseJSONToObject(str) {
var json = JSON.parse(str);
var name = null;
for(var i in json) { //Get the first property to act as name
name = i;
break;
}
if (name == null)
return null;
var obj = new window[name]();
for(var i in json[name])
obj[i] = json[name][i];
return obj;
}
This creates an object of the type represented by the name of the first attribute, and assigns it's values according to the attributes of the object of the first attribute. You could use it like that:
var identifier = parseJSONToObject('{"Identifier": { "name":"uno","contextId":"dos"}}');
console.log(identifier);
Live example
Deserialize JSON into specific/existing JavaScript object
Yes! You can use Object.assign
to overwrite the attributes of an object with another object:
var ClientState = function() { this.userId = ""; this.telephoneState = "UNKNOWN"; this.agentState = "UNKNOWN"; this.muteState = "UNKNOWN"; this.number = ""; this.ready = false;}
var c = new ClientState();console.log('prior assignment: ', c);
Object.assign(c, { "userId": "xyz", "telephoneState": "READY", "agentState": "UNKNOWN", "muteState": "MUTED", "number": "", "ready": false});
console.log('after assignment: ', c);
Deserialize Json to search for a String
Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes
. If you think of your JSON as a Dictionary(Of String, CustomClass)
then using the Paste JSON as Classes using the class information.
When I do that, I get the following output:
Public Class Rootobject
Public Property id As Integer
Public Property description As String
End Class
Using Newtonsoft, you can clean it up a little bit using decorators:
Public Class RootObject
<JsonProperty("id")>
Public Property Id As Integer
<JsonProperty("description")>
Public Property Description As String
End Class
Now that the class is setup, you can use the DeserializeObject method (documentation) to deserialize the JSON into a Dictionary(Of String, RootObject):
Dim dictionary = JsonConvert.DeserializeObject(Of Dictionary(Of String, RootObject))(json)
Once you have the Dictionary setup, you can use the ContainsKey method (documentation) to check if the entered value is in the collection and if the result returns a value then you can get the class:
Private ReadOnly _dictionary As Dictionary(Of String, RootObject)
Sub New()
InitializeComponent()
' this example assumes you have the JSON literal stored in a variable named "json"
_dictionary = JsonConvert.DeserializeObject(Of Dictionary(Of String, RootObject))(json)
End Sub
Private Sub ButtonSearch_Click(sender As Object, e As EventArgs) Handles ButtonSearch.Click
Dim key = TextBoxSearch.Text
If (_dictionary.ContainsKey(key)) Then
Dim result = _dictionary(key)
' do something with result.Id or result.Description
End If
End Sub
Example
https://dotnetfiddle.net/XmplKB
Deserialize json (javascript object) to c# object
I think what you're running into here is that your objects are numbered and you can't name a class with just number. In this case your model doesn't match your JSON so all you're going to get is null. You need to modify your model to match the JSON you have and then you can map that DTO model to something nicer to use in C#.
Here's an example model that deserializes your JSON:
public class auction_id
{
public string name { set; get; }
public IDictionary<int, Sub_auction_id> items { set; get; }
}
public class Sub_auction_id
{
public string pos { get; set; }
public string name { get; set; }
public string address { get; set; }
public string zip { get; set; }
public string coords { get; set; }
}
And then deserialize like so:
public void Deserialize()
{
var auction = JsonConvert.DeserializeObject<IDictionary<int, auction_id>>(json);
}
How to deserialize Json to an object?
var s = "{\r\n \"Status\": \"PLANNED\"\r\n}";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<StatusModel>(s);
The model you have defined is incorrect.
Your model should be like this:
public class StatusModel
{
public string Status { get; set; }
}
Now value will be extracted to this model and you can access the value like:
var value = obj.Status; //"PLANNED"
How to deserialize JSON object into an interface TypeScript
Looks like the JSON.parse(json)
was unnecessary. All I had to do was
const response = await fetch('https://api.codetabs.com/v1/proxy/?quest=http://hamsterland.herokuapp.com/api/users?id=330746772378877954');
const user: User = await response.json();
Thank you @Taplar for the solution.
Related Topics
Detect Blocked Popup in Chrome
Download a Div in a HTML Page as PDF Using JavaScript
Resolving Require Paths with Webpack
Differencebetween Regexp's Exec() Function and String's Match() Function
How to Call a C# Function from JavaScript
How to Save HTML Page as PDF Using JavaScript or Jquery
What's the Difference Between Returning Value or Promise.Resolve from Then()
Angular: Can't Find Promise, Map, Set and Iterator
How to Access Constants in the Lib/Constants.Js File in Meteor
Set a Request Header in JavaScript
Getting Title from Wkwebview Using Evaluatejavascript
Most Efficient Method of Detecting/Monitoring Dom Changes
Use Browser Search (Ctrl+F) Through a Button in Website
Event.Preventdefault() VS. Return False (No Jquery)
Access Parent's Parent from JavaScript Object
How to Display Multiple Google Maps Per Page with API V3