How to stringify/normalize json in C# like JSON.stringify() would

13,222

The problem is that you are comparing having an OBJECT in JS then convert it to JSON, to having a STRING in C# and then convert it to JSON.

If you had a C# object, the equivalent to JSON.stringify() would be just JsonConvert.SerializeObject(myObject). C# doesn't accept JSON syntax (like JS does) to define an object.

On the MDN samples you posted, you see:

console.log(JSON.stringify({ x: 5, y: 6 }));

The c# equivalent would be (run it):

 Console.WriteLine(JsonConvert.SerializeObject(new { x = 5, y = 6 });

But that's just the way C# syntax works (Javascript allows JSON to define objects without having to parse them... C# has a different syntax for defining objects inline -anonymous or not-).

The equivalent in Javascript to the example you posted (having a string, and not an object) would be:

const jsString = '{"test": "test"}';
console.log(JSON.stringify(JSON.parse(jsString)));

Which is a bit different than just using JSON.stringify(), and matches what you are seeing in C# (deserializing then serializing)

Notice also that the syntax Javascript allows to define objects is not necessarily "strict valid JSON"... the above with this string would fail:

const jsString = '{ test: "test" }';

Whereas this way to define an object would be valid:

const jsObject = { test: "test" };

(that's, in fact, the reason you might want to "normalize" it as you call it)


All that said

if deserializing/serializing is a problem as in "looks", just make an extension method... something like:

public static string NormalizeJson(this string input) {
   return JsonConvert.SerializeObject(JsonConvert.DeserializeObject<object>(input));
}

And then you can just do this on any string (if you have added the using on top):

myJsonInput.NormalizeJson();

See it in action

Share:
13,222

Related videos on Youtube

Veksi
Author by

Veksi

Updated on June 04, 2022

Comments

  • Veksi
    Veksi almost 2 years

    I wonder if there's a better, less haphazard feeling, way of doing to JSON strings what JSON.Stringify does than this?

    string json = "{test: 'test'}";
    var stringified = JsonConvert.SerializeObject(JsonConvert.DeserializeObject<dynamic>(json));
    Console.WriteLine(stringified); //Prints {"test":"test"}
    

    It appears there isn't a method kind of normalize the string presentation otherwise in C#. I'm not sure about the new .NET Core 3.0 and its new JSON libraries.

    <edit: To make the comments a bit more visible, there can be an interoperability situation to JSON.stringify all input to Javascript strings be it in object notation or already stringified. So I was wondering if there's a better way of doing the processing as the one I noted. Even better if built into the framework already.

    A playground can be had at MDN Web Docs.

    There is one example at https://github.com/ethereum/wiki/wiki/JavaScript-API#web3tohex where it appears even the same {test: 'test'} JSON object is first stringified and then HEX encoded. There can be cases in C# too where one is reading strings from other sources and the output needs to be in stringified form regardless.

    • Crowcoder
      Crowcoder about 5 years
      What do you mean by "normalize"? What is the reason you deserialize a json string and then immediately serialize it back to how it started? Is it just the quoting?
    • TheGeneral
      TheGeneral about 5 years
      Would it not be better to create a concrete class structure, and seralize that?
    • Veksi
      Veksi about 5 years
      @Crowcoder The example I have there is having a Javascript object I'd like to have as a JSON string for later processing. This later processing can encode it with some other method and the result isn't the same with and without stringifying. TheGeneral Not in this case. The goal is to accept JSON and do as JSON.stringify would to, as accurately as possible.
    • maccettura
      maccettura about 5 years
      Is your example even valid json?
    • Veksi
      Veksi about 5 years
      @maccetura It is. First it's a JS object then stringified to JSON.
  • Veksi
    Veksi about 5 years
    Yep. Maybe I should have emphasized the input for the C# code is plain strings read from some source and can be both in JSON object notation and in stringified form (with potential edge cases) and so far doing that dance with dynamic object appears to give the output of stringified JSON and maybe covers gracefully edge cases, like the one you mentioned. That is, I'm not looking for what's equivalent in the code but close enough in the result, output. And if there's a less hacky feeling way of doing it rather than that dance. It appears there isn't.
  • Jcl
    Jcl about 5 years
    @Veksi I've added an additional comment showing how to convert that to an extension method if you want it "cleaner"
  • Veksi
    Veksi about 5 years
    OK. :) I think this is the closest one can get, apart from naming the method as Stringify, but I don't know if it'd be the right call. I think there indeed isn't a materially better way of achieving this, but maybe this was a good discussion to bounce minds.
  • Jcl
    Jcl about 5 years
    If you want to call it Stringify, I'd avoid putting this as an extension method, and make a static class named Json, with a static method Stringify... note however, that again: JSON.Stringify in Javascript does NOT normalize "json strings". It serializes javascript objects. It's just not the same thing you are doing here