How do I get formatted JSON in .NET

WebSpider 76 Reputation points
2021-08-03T23:56:14.68+00:00

Hi guys.. I wanna make my inputData more readable. i have using Formatting.Indented but the output is still displayed in a line.

        Dim inputData As Object = New With {
                .serviceType = "MOTORCYCLE",
                .delivery = New List(Of Object) From {
                        New With {
                            .toContact = New List(Of Object) From {
                                    New With {
                                        .name = "Bruce Barner",
                                        .phone = "+659855365"
                                    }
                            }
                        }
                },
                .pickup = New List(Of Object) From {
                        New With {
                            .name = "Tony Stark",
                            .phone = "+659855235"
                        }
                }
        }

        Dim body As String = (New JavaScriptSerializer()).Serialize(inputData)
        Response.Write(Newtonsoft.Json.Linq.JValue.Parse(body).ToString(Newtonsoft.Json.Formatting.Indented))

How can i make the output like something below:

{
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ],
  "Price": 3.99,
  "Expiry": "\/Date(1230447600000-0700)\/",
  "Name": "Apple"
}
Developer technologies VB
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-08-04T00:11:03.113+00:00

    Use the “Manage NuGet Packages” command for your project, add a reference to modern System.Text.Json package, then try this code:

    Dim opt As New JsonSerializerOptions With {.WriteIndented = True}
    Dim result As String = JsonSerializer.Serialize(inputData, opt)
    Console.WriteLine(result)
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.