JSON Formatter in C#

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);
}

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

How to format a json string as tree format in c#

I am not sure if it will be fast enough, but it could be a possible solution:

using System.Collections.Generic;
using Newtonsoft.Json;

namespace ConsoleApp1
{
class Program
{
public class Item
{
[JsonProperty("_id")]
public string Guid { get; set; }

[JsonProperty(PropertyName = "company")]
public string Company { get; set; }

[JsonProperty(PropertyName = "id")]
public string Id { get; set; }

[JsonProperty(PropertyName = "parent")]
public string Parent { get; set; }

[JsonProperty(PropertyName = "children")]
public List<Item> Children { get; set; }
}

private static string jsonString = "[{\"_id\":\"5c04fc163838b0772dd9636d\",\"Company\":\"TESTCOMPANY\",\"id\":\"test_uk\",\"parent\":\"\"},{\"_id\":\"5c05181f0ab89a44a969015d\",\"Company\":\"TESTCOMPANY\",\"id\":\"Gateway\",\"parent\":\"test_uk\"},{\"_id\":\"5c0518723838b0772dd9678e\",\"Company\":\"TESTCOMPANY\",\"id\":\"Device1\",\"parent\":\"Gateway\"},{\"_id\":\"5c0518723838b077789636e\",\"Company\":\"TESTCOMPANY\",\"id\":\"Device2\",\"parent\":\"Gateway\"},{\"_id\":\"5c0518723838b0772dd9636e34\",\"Company\":\"TESTCOMPANY\",\"id\":\"Adapter\",\"parent\":\"test_uk\"},{\"_id\":\"5c0518723838b0772dd9636e\",\"Company\":\"TESTCOMPANY\",\"id\":\"AdapterDevice\",\"parent\":\"Adapter\"},{\"_id\":\"5c04fc163838b0772dd93454d\",\"Company\":\"TESTCOMPANY\",\"id\":\"test_us\",\"parent\":\"\"},{\"_id\":\"5c0518723838b0772dd9636e\",\"Company\":\"TESTCOMPANY\",\"id\":\"Device\",\"parent\":\"test_us\"}]";

static void Main(string[] args)
{
var items = JsonConvert.DeserializeObject<List<Item>>(jsonString);

var dictionary = new Dictionary<string, Item>();

foreach (var item in items)
{
if (!dictionary.ContainsKey(item.Parent))
{
dictionary.Add(item.Id, item);
}
else
{
if (dictionary[item.Parent].Children == null)
dictionary[item.Parent].Children = new List<Item>();
dictionary[item.Parent].Children.Add(item);
}
}

string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);

System.Console.WriteLine(json);

System.Console.ReadLine();
}
}
}

I just made a simple console app which uses Newtonsoft.Json library. I think it is the mostly used for such a purposes.

You have to find on your own how to remove parent properties in the result, but it should not be a big deal, I suppose.

how can i make formatted json file in c#

If you're going to be running JsonConvert.SerializeObject anyways, you may have an easier go of it by just creating an anonymous type with your values. The following would get you your desired result:

var item = new
{
LiftPositioner = new[]
{
new
{
LiftMax = 5,
LiftMin = 0
}
},
Temperature = new[]
{
new
{
CH0_Temp = 25,
CH1_Temp = 25
}
}
};
string strJson = JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(strJson);

Which outputs the following:

{
"LiftPositioner": [
{
"LiftMax": 5,
"LiftMin": 0
}
],
"Temperature": [
{
"CH0_Temp": 25,
"CH1_Temp": 25
}
]
}

If you don't want lists for the LiftPositioner and Temperature properties, you could reduce this down to:

var item = new
{
LiftPositioner =
new
{
LiftMax = 5,
LiftMin = 0
},
Temperature =
new
{
CH0_Temp = 25,
CH1_Temp = 25
}
};

Which would yield

{
"LiftPositioner": {
"LiftMax": 5,
"LiftMin": 0
},
"Temperature": {
"CH0_Temp": 25,
"CH1_Temp": 25
}
}

How to write json format in C# string?

Json is the text serialisation of an object. So you simply have to create an object with those property and serialise it. To assit in creating the class that represent your object you can simply paste a Valid Json to Json 2 C#.

public class Notification
{
public string title { get; set; }
public string text { get; set; }
public string sound { get; set; }
}

public class RootObject
{
public string to { get; set; }
public Notification notification { get; set; }
}

And use it like :

var item = new RootObject {
to = "topics/extrafx",
notification = new Notification {
title = variableFoo,
text = variableBar,
sound = "default"

}
};
var result = JsonConvert.SerializeObject(item);

How to convert json format string to json in c#

This is an invalid JSON format, moreover it does not have surrounding array brackets []. Ideally you should fix this at source.

You could do a simple replace

MyLabels = JsonConvert.DeserializeObject<List<Label>>(labelnames = "[" + labelnames.Replace("'", "\"") + "]")

However this may throw an error if any of the values also contain a '.

Therefore, you could create a custom JsonTextReader

        using (var sw = new StringReader("[" + labelnames + "]"))
using (var reader = new MyJsonTextReader(sw))
{
JsonSerializer ser = new JsonSerializer();
MyLabels = ser.Deserialize<List<Label>>(reader);
}
    class MyJsonTextReader : JsonTextReader
{
public override char QuoteChar { get; protected set; } = '\'';

public MyJsonTextReader(TextReader r) : base(r){}
}
class Label
{
public string LabelName;
public bool IsHeader;
}

dotnetfiddle

Convert API Response in JSON format to c# and print values

Well, as the JSON you're getting from the API is a little WEIRD youn need a little different aproach to the 'normal' serializacion.

Better aproach is to get help of a class with each element and a dictionary

Class:

public class Drivers
{
public string Value { get; set; }
public DateTime LastUpdatedTime { get; set; }
public string Status { get; set; }
public double HighLimit { get; set; }
public double LowLimit { get; set; }
public object AlarmValue { get; set; }
}

and then deserialize using Newtonsoft

var myDeserializedDict= JsonConvert.DeserializeObject<Dictionary<string, Drivers>>(text);

After this you got a 'normal' collection inside the Dictionary and can use it as you wish:

        foreach (KeyValuePair<string, Drivers> item in myDeserializedDict) 
{
Console.WriteLine(item.Key + " (Status): " + item.Value.Status.ToString());
Console.WriteLine(item.Key + " (LastUpdated): " + item.Value.LastUpdatedTime.ToString());
[...]
}


Related Topics



Leave a reply



Submit