Goal: Use kendo ui diagram component to draw a department to project workflow
The workflow is structured in the following manner:
Each Department may have multiple Strategies, each Strategy may have multiple Programs and each Program may have multiple projects.
I have a WCF service that when called returns a json string.
The service calls a stored proc that returns XML, in vb.net then I convert that XML into json (using json.net).
service code:
Public Function GetStakeholderRelationshipMatrix(StakeholderId As Integer) As String
Try
conn.Open()
Dim da = New SqlDataAdapter()
sCommand = New SqlCommand("uspGetRelationshipMatrix", conn)
sCommand.CommandType = CommandType.StoredProcedure
sCommand.Parameters.AddWithValue("#StakeholderId", StakeholderId)
xmlDoc.LoadXml(sCommand.ExecuteScalar())
Return JsonConvert.SerializeXmlNode(xmlDoc)
Catch ex As Exception
Return -1
End Try
End Function
XML Data
<Departments>
<Department Id="7" Name="Information Technology Department">
<Strategies Id="21" Name="Increase Revenue">
<Programs Id="45" Name="Program1">
<Projects Id="4" Name="test3" />
</Programs>
<Programs Id="49" Name="Program4">
<Projects Id="2" Name="Test1" />
<Projects Id="3" Name="Test2" />
</Programs>
</Strategies>
</Department>
</Departments>
Json Converted Data:
{"d":"{\"Departments\":{\"Department\":{\"#Id\":\"7\",\"#Name\":\"Information Technology Department\",\"Strategies\":{\"#Id\":\"21\",\"#Name\":\"Increase Revenue\",\"Programs\":[{\"#Id\":\"45\",\"#Name\":\"Program1\",\"Projects\":{\"#Id\":\"4\",\"#Name\":\"test3\"}},{\"#Id\":\"49\",\"#Name\":\"Program4\",\"Projects\":[{\"#Id\":\"2\",\"#Name\":\"Test1\"},{\"#Id\":\"3\",\"#Name\":\"Test2\"}]}]}}}}"}
I am have been unable to bind the data (json) to the diagram component in order to successfully display the workflow. I need help binding the json string to the diagram component.
Kendo code:
<div id="visual"></div>
var dsRelationshipMatrix = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
url: "wcf service return json string",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (result) {
var obj = $.parseJSON(result.d);
if (obj == null) {
options.success([]);
} else {
options.success(obj);
}
},
error: function (result) {
options.error(result)
}
});
}
},
schema: {
data: function (data) {
return data
}
}
}); //closes data source
function createDiagram() {
$("#visual").kendoDiagram({
dataSource: new kendo.data.HierarchicalDataSource({
data: dsRelationshipMatrix,
schema: {
model: {
children: "Strategies"
}
}
}),
layout: {
type: "layered"
},
shapeDefaults: {
visual: visualTemplate
},
connectionDefaults: {
stroke: {
color: "#979797",
width: 2
}
}
});
var diagram = $("#visual").getKendoDiagram();
diagram.bringIntoView(diagram.shapes);
}
After going through the pain for some time, I got it to work and wanted to share that information with everyone. This might not be the perfect way but it is one of the ways to do it.
The key is going to be the structure of the SQL data (extracted as XML).
In SQL I ended up performing a recursive loop that extracts the data and formats it into XML. So a root node of ROOT encompasses an item (Department - there can only be one department) and each hierarchical category has an items section with an item section as a child of items. Wording the structure is rather difficult so...
SQL:
SELECT
--dStakeholder.StakeholderId AS '#Id',
dStakeholder.FunctionalDepartment as 'item/info' ,
'#1696d3' as 'item/colorScheme',
(SELECT
--dStrategy.StrategyId AS '#Id',
dStrategy.StrategyDescription 'item/info',
'#1696d3' as 'item/colorScheme' ,
(Select
--dPrograms.ProgramId as '#Id',
dPrograms.ProgramDescription 'item/info' ,
'#1696d3' as 'item/colorScheme' ,
(Select
--dHeaders.ProjectId as '#Id',
dHeaders.ProjectName 'item/info',
'#1696d3' as 'item/colorScheme'
from
dbo.ProjectHeaders as dHeaders
inner join (select distinct projectid, programid, departmentid from dbo.ProjectHeaders) as pp
on dHeaders.ProjectId = pp.ProjectId
where pp.ProgramId = dPrograms.ProgramId and pp.departmentid = dStakeholder.Stakeholderid
FOR XML PATH(''), TYPE
) as 'item/items'
from
dbo.ProjectPrograms as dPrograms
inner join (select distinct programid, strategyid , departmentid from dbo.ProjectHeaders) as sp
on dPrograms.ProgramId = sp.ProgramId
where sp.StrategyId = dStrategy.StrategyId and sp.departmentid = dstakeholder.stakeholderid
FOR XML PATH(''), TYPE
) as 'item/items'
FROM
dbo.ProjectStrategies as dStrategy
inner join (select distinct strategyid , departmentid from dbo.ProjectHeaders) as bss
on dStrategy.StrategyId = bss.StrategyId
WHERE
dStakeholder.StakeholderId = bss.DepartmentId
FOR XML PATH(''), TYPE
) as 'item/items'
FROM
dbo.Stakeholders as dStakeholder
FOR XML PATH('root'), type
My data from the sql appears in XML in this manner:
<root>
<item>
<info>ERISA Compliance Services Department</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>New Commission</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>Program3</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>test3</info>
<colorScheme>#1696d3</colorScheme>
</item>
</items>
</item>
</items>
</item>
<item>
<info>SAGA Development</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>Program1</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>Test1</info>
<colorScheme>#1696d3</colorScheme>
</item>
</items>
</item>
<item>
<info>Program4</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>Test2</info>
<colorScheme>#1696d3</colorScheme>
</item>
</items>
</item>
</items>
</item>
</items>
</item>
</root>
Now I go through my xml and grab the important information. Code in VB.net. There is a class for item that just list the properties that I would need.
conn.Open()
Dim dt As New DataTable
Dim da As New SqlDataAdapter("uspGetRelationshipMatrix " + Convert.ToString(StakeholderId), conn)
da.Fill(dt)
Dim sb = New StringBuilder()
If dt.Rows.Count <> 0 Then
For Each row As DataRow In dt.Rows
sb.Append(row.Item("Data"))
Next
End If
conn.Close()
xmlDoc.LoadXml(sb.ToString)
Dim itemList As New List(Of Item)
Dim RootNode As XmlNode
RootNode = xmlDoc.SelectSingleNode("/root")
For Each DeptNode As XmlNode In RootNode.ChildNodes
Dim deptItem As New Item
'check to ensure that is not nothing
Dim info As XmlNode = DeptNode.SelectSingleNode("info")
Dim cs As XmlNode = DeptNode.SelectSingleNode("colorScheme")
deptItem.info = info.InnerText
deptItem.colorScheme = cs.InnerText
'Begin items loop for child nodes
Dim stratItems As XmlNode = DeptNode.SelectSingleNode("items")
For Each stratItemNode As XmlNode In stratItems.ChildNodes
Dim stratItem As New Item
Dim stratinfo As XmlNode = stratItemNode.SelectSingleNode("info")
Dim stratcs As XmlNode = stratItemNode.SelectSingleNode("colorScheme")
stratItem.info = stratinfo.InnerText
stratItem.colorScheme = stratcs.InnerText
'place start loop
Dim progItems As XmlNode = stratItemNode.SelectSingleNode("items")
For Each progItemNode As XmlNode In progItems.ChildNodes
Dim progItem As New Item
Dim proginfo As XmlNode = progItemNode.SelectSingleNode("info")
Dim progcs As XmlNode = progItemNode.SelectSingleNode("colorScheme")
progItem.info = proginfo.InnerText
progItem.colorScheme = progcs.InnerText
'place start loop
Dim projItems As XmlNode = progItemNode.SelectSingleNode("items")
For Each projItemNode As XmlNode In projItems.ChildNodes
Dim projItem As New Item
Dim projinfo As XmlNode = projItemNode.SelectSingleNode("info")
Dim projcs As XmlNode = projItemNode.SelectSingleNode("colorScheme")
projItem.info = projinfo.InnerText
projItem.colorScheme = projcs.InnerText
'place start loop
'place end loop
progItem.items.Add(projItem)
Next
'place end loop
stratItem.items.Add(progItem)
Next
'place end loop
deptItem.items.Add(stratItem)
Next
'end items loop
itemList.Add(deptItem)
Next
I then use newtonsoft json in vb.net in order to present the information as a json string.
Json string:
[
{
"info":"ERISA Compliance Services Department",
"colorScheme":"#1696d3",
"items":[
{
"info":"New Commission",
"colorScheme":"#1696d3",
"items":[
{
"info":"Program3",
"colorScheme":"#1696d3",
"items":[
{
"info":"test3",
"colorScheme":"#1696d3",
"items":[
]
}
]
}
]
},
{
"info":"SAGA Development",
"colorScheme":"#1696d3",
"items":[
{
"info":"Program1",
"colorScheme":"#1696d3",
"items":[
{
"info":"Test1",
"colorScheme":"#1696d3",
"items":[
]
}
]
},
{
"info":"Program4",
"colorScheme":"#1696d3",
"items":[
{
"info":"Test2",
"colorScheme":"#1696d3",
"items":[
]
}
]
}
]
}
]
}
]
With the json formatted in this structure, now I just plugged my json to kendo diagram and now you get a visual hierarchical image of flow.
Related
json data not binding into table
controller code
$http(
{
method: 'post',
url: 'Service.asmx/WPGetDS',
data: $.param({ as_sql: "select * from testtab", strConKey: "Etech" }),
dataType: 'json',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data, status, headers, config) {
var myjson = JSON.parse(data);
$scope.dtDioSearch = myjson;
console.log(myjson);
}).error(function (data, status, headers, config) {
console.log(data);
});
Web Service Code
Public Sub WPGetDS(ByVal as_sql As String, ByVal strConKey As String)
Dim dt As New DataTable()
Dim conGlobal As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings(strConKey).ConnectionString)
Dim a(0) As String
Dim dr As DataRow
Dim dtDataTable As DataTable
If conGlobal.State = ConnectionState.Closed Then conGlobal.Open()
Dim SDA = New SqlDataAdapter(as_sql, conGlobal)
Dim DS As DataSet = New DataSet()
Dim data As New WPData
Dim js As New JavaScriptSerializer()
Dim lCmdSql, lCmdErr As New SqlCommand
Try
dtDataTable = New DataTable("Table")
Dim dcolSrNo As DataColumn
dcolSrNo = New DataColumn("SlNo")
dcolSrNo.AutoIncrement = True
dcolSrNo.AutoIncrementSeed = 1
dcolSrNo.AutoIncrementStep = 1
dtDataTable.Columns.Add(dcolSrNo)
DS.Tables.Add(dtDataTable)
SDA.Fill(DS, ("Table"))
SDA.Dispose()
data.Message = ConvertDataTableTojSonString(DS.Tables(0))
Context.Response.Write(js.Serialize(data.Message))
Catch ex As Exception
dt.Columns.Clear()
dt.Columns.Add("Error")
dr = dt.NewRow
dr.Item("Error") = ex.Message.Trim
dt.Rows.Add(dr)
DS.Tables.Add(dt)
conGlobal.Close()
data.Message = ConvertDataTableTojSonString(DS.Tables(0))
Context.Response.Write(js.Serialize(data.Message))
Finally
If conGlobal.State = ConnectionState.Open Then conGlobal.Close()
End Try
End Sub
HTML Code
<div class="table-responisive">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="erdata in dtDioSearch track by $index">
<td>{{erdata.SlNo}}</td>
<td>{{erdata.Test}}</td>
</tr>
</tbody>
</table>
</div>
Console Json data
[{"SlNo":1,"test":"test"},{"SlNo":2,"test":"test"},{"SlNo":3,"test":"test"},{"SlNo":4,"test":"test"},{"SlNo":5,"test":"test"},{"SlNo":6,"test":"test"},{"SlNo":7,"test":"test"},{"SlNo":8,"test":"test"},{"SlNo":9,"test":"test"},{"SlNo":10,"test":"test"},{"SlNo":11,"test":"test"},{"SlNo":12,"test":"test"},{"SlNo":13,"test":"test"},{"SlNo":14,"test":"test"},{"SlNo":15,"test":"test"},{"SlNo":16,"test":"test"},{"SlNo":17,"test":"test"},{"SlNo":18,"test":"test"},{"SlNo":19,"test":"test"},{"SlNo":20,"test":"test"},{"SlNo":21,"test":"test"},{"SlNo":22,"test":"test"}]
My problem is json data not bind to the html table. in firefox there was an error shown not well-formed in console. please help...
The first argument of your success callback will be a JavaScript object containing many properties including a data property whose value is the parsed JavaScript object based on the JSON returned by your API. Trying to parse a JavaScript object will result in error.
Try modifying the success method to:
.success(function (response, status, headers, config) {
var myjson = response.data;
$scope.dtDioSearch = myjson;
});
Public Function GetJSon(ByVal dt As DataTable) As List(Of Dictionary(Of String, Object))
Dim rows As New List(Of Dictionary(Of String, Object))
Dim row As Dictionary(Of String, Object)
'Return JsonConvert.SerializeObject(dt).ToList
'Return JSONString
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)
For Each col As DataColumn In dt.Columns
If col.DataType = GetType(Date) Then
Dim dtt As DateTime = DateTime.Parse(dr(col).ToString())
row.Add(col.ColumnName, dtt.ToString("dd-MM-yyyy hh:mm:ss"))
Else
row.Add(col.ColumnName, dr(col))
End If
Next
rows.Add(row)
Next
Return rows
End Function
#tj thank you for your support. the problem is json return string and i changed it to array list
Hey all I am having difficultys in making this string JSON that I have into an object so that I can use it like this:
json("go")("to")("needed")("spot").toString
and get my value.
Currently the XML to JSON looks like this:
{
"?xml": {
"#version": "1.0",
"#encoding": "UTF-8"
},
"data": {
"recordCount": "1",
"metadata": {
"elementType": [
{
"name": "F_Paragraphtext",
"uiType": "textArea",
"dataType": "string",
"label": "Text String",
"dataLabel": ""
}
]
},
"records": {
"F_Form1": {
"#application_uid": "2a667c59-225c-4954-8e04-77bb083e5180",
"#uid": "61f876f4-9760-4013-85bb-37965cff1fb6",
"F_SingleLine": "test",
"F_Paragraphtext": "{\"Data\":{\"DevisionName\":\"testing service after added field\",\"DevisionCode\":\"test\",\"CodeInString\":\"test^test|4/15/2015|50%|test^test|4/15/2015|25%|test^test|4/23/2015|50%~test^test|4/23/2015|N/A|test^test|4/8/2015|N/A|test^test|3/31/2015|N/A~test^test|4/10/2015|N/A|test^test|5/1/2015|50%|test^test|4/18/2015|N/A~test^test|3/30/2015|50%|test^test|4/24/2015|50%|test^test|5/9/2015|100%~test^test|3/30/2015|25%|test^test|3/30/2015|100%|test^test|4/11/2015|75%\"}}"
}
}
}
}
And I am trying to get the value for F_Paragraphtext, #application_uid & #uid.
The VB.net code I have:
Dim doc1 As XmlDocument = New XmlDocument()
doc.LoadXml(serverResponse)
Dim json1 As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented)
jsreader = New Newtonsoft.Json.JsonTextReader(New StringReader(json1))
Try
json = DirectCast(New Newtonsoft.Json.JsonSerializer().Deserialize(jsreader), Newtonsoft.Json.Linq.JObject)
Catch ex As Exception
MsgBox(ex.Message)
End Try
For Each Row In json("data")("records")(febFormID)
Try
dName = json("#application_uid").ToString
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
While Row value is:
{"#application_uid": "2a667c59-225c-4954-8e04-77bb083e5180"}
The error falls on the dName = Row("#application_uid").ToString. The error is Object reference not set to an instance of an object..
Not quite sure what all I am missing in order to be able to retrieve the Row values but apparently its something....
...making this string JSON that I have into an object so that I can use it like this:
json("go")("to")("needed")("spot").toString
I am trying to get the value for F_Paragraphtext, #application_uid & #uid.
Dim jstr As String = File.ReadAllText(filename)
Dim myJ = JObject.Parse(jstr)
Console.WriteLine("{0} == {1}", "F_Paragraphtext",
myJ("data")("records")("F_Form1")("F_Paragraphtext"))
Console.WriteLine("{0} == {1}", "#application_uid",
myJ("data")("records")("F_Form1")("#application_uid"))
Console.WriteLine("{0} == {1}", "#uid",
myJ("data")("records")("F_Form1")("#uid"))
Output:
F_Paragraphtext == {"Data":{"DevisionName":"testing service after added field","DevisionCode":"test","CodeInString":"test^test|4/15/2015|50%|test^test|4/15/2015|25%|test^test|4/23/2015|50%~test^test|4/23/2015|N/A|test^test|4/8/2015|N/A|test^test|3/31/2015|N/A~test^test|4/10/2015|N/A|test^test|5/1/2015|50%|test^test|4/18/2015|N/A~test^test|3/30/2015|50%|test^test|4/24/2015|50%|test^test|5/9/2015|100%~test^test|3/30/2015|25%|test^test|3/30/2015|100%|test^test|4/11/2015|75%"}}
#application_uid == 2a667c59-225c-4954-8e04-77bb083e5180
#uid == 61f876f4-9760-4013-85bb-37965cff1fb6
Hey all I am getting the following error at random spots in my code:
Object reference not set to an instance of an object.
I know why I am getting it. It does not find the correct property that I have it looking for and therefore it gives the error. Some may have that property and some, as this error shows, may not.
What can I do in order to check first to make sure it has that property? Currently I just have a Try/catch method in place so it can keep going if it does find something that's not there.
For Each Row In json("data")
Try
thePostID = DirectCast(Row("id").ToString(), String)
thePostType = DirectCast(Row("type").ToString(), String)
thePosterID = DirectCast(Row("from")("id").ToString(), String)
thePosterName = DirectCast(Row("from")("name").ToString(), String)
Catch ex As NullReferenceException
msgbox("Did not find that particular property!")
End Try
Next
update
{
"data": [
{
"id": "102zzz533zz_10z52zz9zzzz94z3",
"from": {
"id": "102zzzzz95zzz7",
"name": "Jim zzzzz"
},
"likes": {
"data": [
{
"id": "85zzzzz35zzzz0",
"name": "Anna zzzzz"
},
{
"id": "10zzzz93z31zzzzz",
"name": "Vanessa zzzz zzzz"
},
{
"id": "1zzz44zzz48731z6",
"name": "Leta zzzzzz"
}
],
"paging": {
"cursors": {
"after": "MTAyMdfasdfwrtMTkyNg=",
"before": "ODUasdfasrU5Mwerw"
}
}
}
etc...
This JSON above follows in the same data path as all the others.
Using #Andrews code below:
thePostLikes = NullSafeSelect(Row, "likes.data.id")
If thePostLikes <> "NA" Then
For Each Row2 In json("likes")("data")
thePostLikesID += NullSafeSelect(Row2, "id") & ","
thePostLikesName += NullSafeSelect(Row2, "name") & ","
Next
End If
The value of thePostLikes is always Nothing
There may be a more graceful way to do this that's built in to JSON.NET, but here's a helper function that will just return Nothing if the path you supply doesn't exist:
Function NullSafeSelect(ByVal obj As JToken, ByVal path As String) As String
Dim result As String = Nothing
Dim value As JToken = obj.SelectToken(path, False)
if (value IsNot Nothing)
result = value.ToString()
End If
Return value
End Function
You would call it from your loop like this:
For Each row in json("data")
Dim thePostID As String = NullSafeSelect(row, "id")
Dim thePostType As String = NullSafeSelect(row, "type")
Dim thePosterId As String = NullSafeSelect(row, "from.id")
' ... etc
Next
Note that you do not need the DirectCast because the return type of the function is already String.
I'm, Having trouble passing JSON data into the Jstree.
Following is my Jstree
$("#tree")
.bind("open_node.jstree", function (event, data) {
console.log(data.rslt.obj.attr("id"));
})
.jstree({
"plugins" : ["themes", "json_data", "ui"],
"json_data" : {
"data": [{"data":'Top Level - ',"state":'closed',"attr":{"seq_no":341386}}],
"state" : "open",
"ajax": {
"type": 'POST',
"dataType": 'json',
"data": {"action": 'getChildren'},
"url": function (node) {
var nodeId = node.attr('seq_no');
return 'ajax/test.jsp?seq_no=' + 341386;
},
"success": function (new_data) {
return new_data;
}
}
}
});
And test.jsp looks like this:
RecordCollection result=null;
PlsqlSelectCommand selCmd = null;
String sErrorMsg = "";
String sqlSelect;
OutputFormat format = new OutputFormat( doc ); //Serialize DOM
StringWriter xmlOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer( xmlOut, format );
serial.serialize(doc);
JSONObject jsonObject = XML.toJSONObject(xmlOut.toString());
<%=jsonObject%>
The problem is JSON data isnt passed into the jstree. thus I cant set my children nodes. I've tried so hard but can't get this working.
Is there something else I need to do in order to pass this JSON string into the jstree.
My jstree works when the data feed is hard-coded.
Any help is much appreciated.
I have the below Json (wf.json)
{
"workflow":{
"template":"Analysis1",
"start":{
"instance":"HDA_run1",
"user":"symtest",
"date":"3-Mar-2012",
"timestamp":"1330948220475"
},
"host":{
"name":"bartla",
"user":"symtest1",
"password":"symtest1",
"installpath":"",
"product":""
},
"javadump":{
"pid":"8989",
"corefilename":"",
"heapdump":"",
"stack":"",
"JAVA_HOME":""
},
"mat":{
},
"email":{
"to":"ars#gmail.com",
"subject":"",
"message":""
},
"end":{
}
}
}
As you can see there are 7 items (or sub headings inside main heading workflow). Under each item it can have another set of properties eg: email (item) has 3 properties ("name":"value").
So based on the number of properties I need to be able to create controls (Text) in my Flex 3 UI.
I read here that actionjson is 5-6x faster than the as3corelib, but I am not able to find any example code for it. The actionjson doc says it function the same way as corelib, so I even tried import com.adobe.serialization.json.JSON; JSON.decode(rawData) but it is unable to find JSON.
Below is my code
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" minWidth="955" minHeight="600"
creationComplete="service.send()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
private function onJSONLoad(event:ResultEvent):void
{
//get the raw JSON data and cast to String
var rawData:String = String(event.result);
//Alert.show(rawData); This prints my JSON String
var obj:Object = decodeJson(rawData);
/*error call to possibly undefined method decodeJson*/
Alert.show(obj.toString());
}
]]>
</mx:Script>
<mx:HTTPService id="service" resultFormat="text"
url="/cjb/wf.json"
result="onJSONLoad(event)" />
</mx:Application>
Please help me fetch name, values if any from each item. Thanks
Is it not possible to directly fetch json data from an object (not custom made) like it is done in jquery?
Update with Flex Build Path
If the fastest parser is what you want, then you'll want use native JSON parsing. Its usage is as simple as this:
var result:Object = JSON.parse(event.result);
trace(result.workflow.template); //traces "Analysis1"
The JSON class is located in the root package, so no need to import anything. You can find information on its usage in the docs.
However native JSON is only available for Flash Player 11 or higher, which means you'll have to target at least that player version. Since your compiling a Flex 3 application, it will target Flash Player 9 by default. If your requirements don't prohibit you from targeting FP11+, the easiest fix is to compile with the Flex 4.6 (or higher) SDK. The screenshot in your question shows that you're using Flex 3.5, so you'll have to change that in the "build path" settings.
If you wish to traverse the resulting object dynamically, you can do it with a simple 'for' loop:
//workflow is the root node of your structure
var workflow:Object = result.workflow;
//iterate the keys in the 'workflow' object
for (var key:String in workflow) {
trace(key + ': ' + workflow[key]);
}
//template: Analysis1
//start: [Object]
//host: [Object]
//...
If you want to do it recursively, you can check whether a value is an Object or not:
if (workflow[key] is Object) {
//parse that node too
}
else {
//just use the value
}
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import com.adobe.serialization.json.JSON;
[Embed(source="assets/test.json",mimeType="application/octet-stream")]
private var json_file:Class;
protected function button1_clickHandler(event:MouseEvent):void
{
trace("Hello from Flex Debugging!");
var bytes:ByteArray = new json_file();
var json:String = bytes.readUTFBytes(bytes.length);
trace(json);
var arr:Object = JSON.decode(json);
for (var keyname:String in arr)
{
trace ( keyname + ": " + arr[ keyname ] );
}
grid.dataProvider = arr;
}
]]>
</mx:Script>
<mx:DataGrid id="grid" right="10" left="10" top="10" bottom="10">
<mx:columns>
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Age" dataField="age"/>
</mx:columns>
</mx:DataGrid>
<mx:Button x="538" y="45" label="Get Json" click="button1_clickHandler(event)"/>
</mx:WindowedApplication>
test.json
{
"name": "dibneg",
"age" : "67",
"sex": "female",
"imagePath": "kamil.jpg"
}
After following solution from RIAstar, this is what I did (both Flex 3.5 compiler & 4.6 compiler code)
Flex 3.5 compiler using as3corelib.swc for JSON
import com.adobe.serialization.json.JSON;
private var temp:String ='{"workflow":{ "template":"HeapDumpAnalysis", "start":{ "instance":"HDA_run1", "user":"symtest", "date":"3-Mar-2012", "timestamp":"1330948220475" }, "host":{ "name":"estilo", "user":"symtest1", "password":"symtest1", "installpath":"", "product":"" }, "javadump":{ "pid":"8989", "corefilename":"", "heapdump":"", "stack":"", "INFA_HOME":"" }, "mat":{ }, "email":{ "to":"vsatwik#informatica.com", "subject":"", "message":"" }, "end":{ }}}';
private function test():void
{
var obj = JSON.decode(temp);
var workflow:Object = obj.workflow;
for (var key:String in workflow) {
trace(key + ': ' + workflow[key] + (key is String) + ", " + (workflow[key] is String));
}
}
output
javadump: [object Object]true, false
template: HeapDumpAnalysistrue, true
host: [object Object]true, false
end: [object Object]true, false
mat: [object Object]true, false
email: [object Object]true, false
start: [object Object]true, false
Flex 4.6 compiler using native Json parsing
private var temp:String ='{"workflow":{ "template":"HeapDumpAnalysis", "start":{ "instance":"HDA_run1", "user":"symtest", "date":"3-Mar-2012", "timestamp":"1330948220475" }, "host":{ "name":"estilo", "user":"symtest1", "password":"symtest1", "installpath":"", "product":"" }, "javadump":{ "pid":"8989", "corefilename":"", "heapdump":"", "stack":"", "INFA_HOME":"" }, "mat":{ }, "email":{ "to":"ars#gmail.com", "subject":"", "message":"" }, "end":{ }}}';
private function test():void
{
var result:Object = JSON.parse(temp);
var workflow:Object = result.workflow;
for (var key:String in workflow) {
trace(key + ': ' + workflow[key] + (key is String) + ", " + (workflow[key] is String));
}
}
output
javadump: [object Object]true, false
mat: [object Object]true, false
end: [object Object]true, false
email: [object Object]true, false
host: [object Object]true, false
start: [object Object]true, false
template: HeapDumpAnalysistrue, true
import com.adobe.serializers.json.JSONDecoder;
var JSON:JSONDecoder = new JSONDecoder();
var result:Object = JSON.decode(JSON_STRING);
that worked for me
then you can either construct new object type(s) or jsut access values either
result.template
or
result['template']
the latter is good for dynamic valus/keys needed rather than known key values