How to Get Formatted Json in .Net Using C#

How to write a JSON file in pretty format using .Net

After having a gander and attempting myself this is what I found:
You first have to deserialize the string then serialize it again.

EDIT: Took your code as well and got the desired output also like others in comment have said. I tweaked to use JToken instead of JValue and all is good.

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
var item = "{\"messageType\":\"0\",\"code\":\"1\"}";

var t = JsonConvert.DeserializeObject(item);
var x = JsonConvert.SerializeObject(t, Formatting.Indented);

string sPrettyStr;
var item2 = "{\"messageType\":\"0\",\"code\":\"1\"}";
sPrettyStr = JToken.Parse(item2).ToString(Formatting.Indented);

Console.WriteLine(x);
Console.WriteLine(sPrettyStr);
Console.ReadLine();
}
}
}

Credit to Frank from here

JSON formatter in C#?

This worked for me using System.Text.Json in .Net Core 3.1

 public string PrettyJson(string unPrettyJson)
{
var options = new JsonSerializerOptions(){
WriteIndented = true
};

var jsonElement = JsonSerializer.Deserialize<JsonElement>(unPrettyJson);

return JsonSerializer.Serialize(jsonElement, options);
}

Displaying JSON in a gridview format C#

Ok, if you look close, we have the first two rows, and they are repeating data.

Then the next set of columns is a child table.

In effect, this is what we have:

public class Class1
{
public string[] sentence { get; set; }
public string[] sentenceNbr { get; set; }
public string[][] tokens { get; set; }
public string[][] pos { get; set; }
public string[][] ner { get; set; }
public string[][] lemmas { get; set; }
}

Note how the first two columns are array of string[], but the last 4 columns are in fact a string[] of a string[] (nested array).

Unfortantly, the gridview can't really display that.
but, gridview, listview, repeater, datalist - they ALL can take the FIRST two columns.

So, we could droop in a repeater - or a datalist (they both are rather close in what they do - repeat data).

So, say we have this DataList:

I JUST have the first two columns.

        <asp:Datalist ID="MyDataList" runat="server" OnItemDataBound="MyDataList_ItemDataBound">

<ItemTemplate>

<div style="float:left">
<h3>Sentance</h3>
<asp:Label ID="Sentence" runat="server" Text='<%# Eval("sentence") %>'
Width="300px"
></asp:Label>
</div>
<div style="float:left">
<h3>Nbr</h3>
<asp:Label ID="sentenceNbr" runat="server" Text='<%# Eval("sentenceNbr") %>'
Width="80px"></asp:Label>
</div>
</ItemTemplate>
</asp:Datalist>

And now our code to load:

    protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadMyData();
}

void LoadMyData()
{
string strJSON = "";
strJSON = File.ReadAllText(@"c:\test7\udata.txt");

strJSON = "{ 'myroot' :" + strJSON + "}";
DataSet MyTables = new DataSet();
MyTables = JsonConvert.DeserializeObject<DataSet>(strJSON);

MyDataList.DataSource = MyTables;
MyDataList.DataBind();

}

Note how I had to add a "root" to your json data.

Ok, so now we see this:

Sample Image

Hey, not bad at all!!!!

Now the additonal columns - they just don't work with above.

but that means we have to NEST and drop in a grid into the above DataList/Repeater control.

Ok, lets do that. So to above, right below the first two lables, we drop in this:

 <div style="margin-left:25px">
<asp:GridView ID="GridView2" runat="server"
CssClass="table table-condensed"></asp:GridView>
</div>

Now, we have to fill that up. I am REALLY trying to keep this code down, but I can't think of a better way (where is a linq and lamda expression expert when you need one???).

However, this seems to work:

So we are going to use what is called the data bind event. This is much the same for a gridview, listview, repeater etc. (the beauty of .net is once you learn one, then you know them all).

So, we will get the current data row we are bindings.

Create a fake table for the 4 multi-value columns
shove the data into that fake table, and then shove the table into that gridview.

It not TOO much code, but VERY close to the limits of what is practical on SO.

So, this works:

    protected void MyDataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
GridView gv = (GridView)e.Item.FindControl("GridView2");
DataRowView OneDataRow = (DataRowView)e.Item.DataItem;

DataTable rstData = new DataTable();
rstData.Columns.Add("tokens");
rstData.Columns.Add("pos");
rstData.Columns.Add("ner");
rstData.Columns.Add("lemmas");

for (int ChildRow = 0;ChildRow < ((string[])OneDataRow["tokens"]).Length;ChildRow++) {
// add new row
DataRow NewRow = rstData.NewRow();
foreach(DataColumn myCol in rstData.Columns)
{
// add each column value
NewRow[myCol.ColumnName] = ((string[])OneDataRow[myCol.ColumnName])[ChildRow].ToString();
}
rstData.Rows.Add(NewRow);
}
gv.DataSource = rstData;
gv.DataBind();
}

not too bad, and not too messy.

So, I think you can see what we are doing here.

Output:
Sample Image

Create JSON File with Format C#

Here:

string json = "\"Result\": [\r\n    [\r\n      \"Date\",\r\n      \"Name\",\r\n      \"Address\",\r\n      \"Age\"\r\n    ],\r\n    [\r\n      \"MMDDYYYY\",\r\n      \"Name1\",\r\n      \"Add1\",\r\n      \"15\"\r\n    ],\r\n    [\r\n      \"MMDDYYYY\",\r\n      \"Name2\",\r\n      \"Add2\",\r\n      \"20\"\r\n    ],";
var withoutEnter = json.Replace(Environment.NewLine, "");
var splited = withoutEnter.Split('[');
var formattedJson = splited[0];
for (int i = 1; i < splited.Length; i++)
{
formattedJson = formattedJson + "[" + splited[i] + "\n";
}

I have copy-pasted your json sample and parsed it to remove all enters, then added back enter for each group. Sorry for the messy code :)



Related Topics



Leave a reply



Submit