0

I am looking for this code: https://dotnetfiddle.net/80dz3V

using System; using Newtonsoft.Json;

public class Program
{

    public class Product
    {
        public string Name {get; set;}
        public DateTime Expiry {get; set;}
        public string[] Sizes {get; set;}
    }

    public void Main()
    {
        Product product = new Product();
        product.Name = "Apple";
        product.Expiry = new DateTime(2008, 12, 28);
        product.Sizes = new string[] { "Small" };

        string json = JsonConvert.SerializeObject(product);
        Console.WriteLine(json);

        object str = "test";


        json = JsonConvert.SerializeObject(str);
        Console.WriteLine(json);
    }
}

To correctly handle Product but to return just test and not "test"

Output:

{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]}
"test"

Wanted Output

{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]}
test

I understand I could just use a wrapper and check for as but I am curious on what if any JSON.net options are available that can accomplish this?

CuriousDeveloper
  • 849
  • 2
  • 8
  • 27
  • 2
    I wouldn't expect any - `SerializeObject` is meant to return valid JSON, and an unquoted string just isn't valid JSON. It's an odd requirement IMO. (So I'd write a wrapper if I were you, if you really have this odd requirement.) – Jon Skeet Apr 05 '18 at 16:52
  • the REST service is odd, as part of its post parameters it accepts either a value (1,2,3, test) or a json object. (`version=2&things={ "x": [1, 2, 3] }`) But I agree, it's a weird request and perhaps a wrapper is better to convey intent – CuriousDeveloper Apr 05 '18 at 17:58
  • Use `JRaw` instead of `string` as shown in [Get Raw json string in Newtonsoft.Json Library](https://stackoverflow.com/q/10757450/3744182) and [Json.NET - prevent re-serializing an already-serialized property](https://stackoverflow.com/q/32850259/3744182). But the string `test` without quotes is **invalid JSON** so I wouldn't actually do this unless you know in advance the string is well-formed JSON. Forked fiddle: https://dotnetfiddle.net/mR5WJ7 – dbc Apr 05 '18 at 18:49

1 Answers1

-1

Well if your product is a viewModel maybe you can use automapper to return it like Json or you can use the following method with newtonsoft

var jsonObject = new JObject
    {
         {"Property1", Obj.Prop1},
         {"Property2", Obj.Prop1 },
         {"Property3", Obj.Prop1 },
         {"Property4", Obj.Prop1 }
    };

For example the result would be:

{"Property1": "Test", "Property2": 1, "Property3": "ABC123", "Property4": 123.21 }
M_Armendariz
  • 150
  • 9