Creating JSON from C#

I am creating a JSON object in C#… I know i can create my own json text the “hard” way… but i also know that there is standard microsoft programming that will allow the creation of json object, and add objects into that… and then to “serialize” the object using Javascript.
BUT… my problem is: How do I create a JSON ARRAY inside the object?
example of what I want the JSON object to look like… I want to create the array PartList inside the array PlantList… how do I add a new row?

{"PlantList":[{
  "Plant":"MfgSys",
    "PartList":[
      {"partNum":"1032knut"},
      {"partNum","1042knut"}
    ]
  },
  "Plant":"Plant2",
    "PartList":[
      {"partNum":"1032knut"},
      {"partNum","1042knut"}
    ]
  }
}

FYI, I am using
System.Web.dll
System.Web.Extensions.dll */

Also using commands such as:

var orderData = js.Deserialize<dynamic> (JSonString); //deserialze the JSON
string jsonout = js.Serialize (orderData);

Is this for Epicor UI or Epicor BPM ? :slight_smile:

Both Epicor Client and Epicor Server Side /Assemblies/ ship with Newtonsoft.Json.dll perhaps the best option is to see if you can make use of Newtonsoft, its very popular.

2 Likes

Copy your text above, then paste special in VS

This is for a BPM that will generate JSON for passing to another process. I was hoping to find something natural in regular C# that I was missing… I had found Newtonsoft, but since C# already CAN parse out JSON, and since it can create them I thought maybe I was simply missing the Array piece.

The only reason I suggested Newtonsoft is because Epicor Ships with it and it claims to perform 250% faster than JavaScriptSerializer. In addition it seems to support alot and gives you a peace of mind. :slight_smile:

2019-02-05_2219

Docs: Serialize a Dictionary
LINQ to JSON Docs: Convert JSON to Collection

If anyone is curious:
2019-02-05_2206
2019-02-05_2214

5 Likes

Wow… ok… I didn’t know this… I will check it out…
You all might be surprised what is being built with this!

1 Like

Tell us more… :slight_smile:

This is cool, I didnt know you can LINQ Query JSON with it =) Querying JSON with LINQ

actually, you can do the linq query of json without newton… with the line:

var orderData = js.Deserialize<dynamic> (JSonString); //deserialze the JSON

the data is now something you can query and reference by field name.

I second the use of Newtonsoft. It’s been solid for us in BPMs that integrate with some other services. They’ve given no trouble for two years plus, 10.1.400 on until now.

does anyone have any simplified sample code showing it in use in a BPM? (not wanting your coding secrets… just some example lines of code).

I confess I am no expert in this area. I do have working JSON code using Newtonsoft though, and if I get what you’re trying to do then the relevant snippet would be

dynamic consignment = new JObject();
	consignment.consignmentNumber = null;
	consignment.consignmentRef = null;
	consignment.parcels = new JArray();
	consignment.deliveryDetails = deliveryDetails;
	consignment.networkCode = "1^" + netWorkCode;
	consignment.numberOfParcels = numberOfParcels;
	consignment.totalWeight = Math.Round((decimal?)totalWeight ?? 0M,1).ToString();
	consignment.shippingRef1 = ref1;
	consignment.shippingRef2 = ref2;
	consignment.shippingRef3 = ref3;
	consignment.customsValue = null;
	consignment.deliveryInstructions = deliveryInstructions;
	consignment.parcelDescription = string.Empty;
	consignment.liabilityValue = null;
	consignment.liability = false;

dynamic shipment = new JObject();
	shipment.job_id = null;
	shipment.collectionOnDelivery = false;
	shipment.invoice = null;
	shipment.collectionDate = DateTime.Today;
	shipment.consolidate = true;
	shipment.consignment = new JArray(consignment);
2 Likes

One thing to add here is that MSFT is investing in JSON efforts in the next version of dotNet Core - The future of JSON in .NET Core 3.0 · Issue #27761 · dotnet/runtime · GitHub

The use of SPAN is a huge perf boost and if you are geeky, definitely look up it’s use and what it allows you to do outside of ERP BPMs and the like.

SAFE HARBOR
E10 is not dotNet Core compliant - yet - no roadmap on that but since MSFT is seemingly putting all new investment into dotNet Core, it only makes sense for Epicor to continue to monitor.
As it evolves, we will position us and you for it when it matures to a state we can possibly migrate Epicor ERP to it. We have had many chats with MSFT on Core - especially EF Core. We have even done pull requests on bugs in it already as we are obviously a huge user of EF. No announcements but rest assured we continue to maintain conversations with MSFT about where their platforms are going to not leave you behind.

6 Likes

It’s pretty straight forward actually, you can even use inline objects to generate your JSON

var obj = new
            {
                EmpID = "Larry",
                Name = "Larry The Man",
                Shift = new[] { new  { StartTime = "1 AM" }, //Array
                                new  { StartTime = "2 PM"}
                              }
            };

string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

Note the vary inline anonymous object can contain arrays or other objects. As shown above.

3 Likes

We’ll be ready for our Blazor when it arrives. :shushing_face:

2 Likes

LOL, Blazor is interesting.
I assumed MSFT would do that for Silverlight a gazillion years ago and harassed Scott Gu for ‘down browser support’ way back when. I assumed ROTOR would be competing with javascript years ago in the browser but MSFT was too far ahead in thinking at the time and the browsers were not ready - and MSFT reputation had not been healed.
Now that the world caught up, libuv became hot in the node.js world, that thinking is back and folks are ready for it since webassembly is all the craze.
It will be interesting to see if they fully embrace it or if its just a prototype for Daniel Roth to play with and show off. We met with Daniel Roth a couple of months ago on dotNet futures when meeting a bunch of the MSFT rockstar geeks on the Azure futures. Its cool tech. Is it biz ready? TBD.

1 Like

When WebAssembly became a WC3 standard AND Apple got on board then I started taking this seriously. IMHO, the problem with Silverlight was it wasn’t standard and yet another plug in but that’s not an issue here. Heck the miners love WebAssembly! :rofl:

Do I think biz types might like C# over the JS Framework of the month? :man_shrugging:

1 Like

OK. I’m curious. What can you do with Jason?

image

Huge thanks to all that helped… I was able to gather from examples above, as well as several web examples to build a template for building a multi-level JSON data…
In my case below, I am using the Product Configurator inputs as values, and I have a “pretend” loop for Shipments, and pretend loop for Parts within that shipment… it is creating the json as desired. (My pretend loops will be replaced with real for-each statements).


dynamic jsonData;
dynamic shipmentRow;
dynamic partRow;

jsonData = new JObject();	//new clear record
jsonData.shipments = new JArray() as dynamic;	//adds "shipments" as a new array in the jsonData

//pretend top of Shipments loop
//for each shipment

shipmentRow = new JObject();
shipmentRow.plantID = Inputs.SiteID_Chr.Value;
shipmentRow.NewTestField = "abc";

bool custFound=false;

if (Inputs.CustNum_dec.Value == 0){
	if (Inputs.CustomerID_Chr.Value != ""){ 
		shipmentRow.custID= Inputs.CustomerID_Chr.Value;
		custFound=true;
	}
} else {
	shipmentRow.custNum=Convert.ToInt32(Inputs.CustNum_dec.Value) ;
	custFound = true;
}

if (custFound && "True,False".Contains(Inputs.cTrk_Cmb.Value)) 
	shipmentRow.cTrk=Inputs.cTrk_Cmb.Value;

if (Inputs.leadTime_num.Value != 0)
	shipmentRow.leadTime=Convert.ToInt32(Inputs.leadTime_num.Value);

if (Inputs.NotBeforeDate_dte.Value != null) 
	shipmentRow.notBeforeDate= Inputs.NotBeforeDate_dte.Value.ToString();

//pretend loop for parts

if (Inputs.partNum_Chr.Value != ""){

	shipmentRow.partList = new JArray() as dynamic;	//adds partlist to the Shipment ROW 

	//line 1
	partRow = new JObject();		//clear the part row
	partRow.partNum = Inputs.partNum_Chr.Value;
	shipmentRow.partList.Add(partRow);

	//pretend to add a second part
	partRow = new JObject();		//clear the part row
	partRow.partNum = "asdf";
	shipmentRow.partList.Add(partRow);
}

jsonData.shipments.Add(shipmentRow);
//pretend end of shipments loop

Inputs.jsonOutput_edt.Value = JsonConvert.SerializeObject(jsonData);
3 Likes

ALSO see this really good example of using Newton JSON to build date for an ALBUM list with the list of SONGS for each album. Easy to understand with lots of examples

3 Likes