12

I am trying to serialize a C# object into a Json object. That will then be submitted to the Salesforce API, and create an application. Right now I have the C# object serialized into a Json string, but I need it to be an object.

Here is my C# object along with accompany serialization.

Customer application = new Customer { 
    ProductDescription = "gors_descr " + tbDescription.Text, 
    Fname = "b_name_first " + tbFName.Text, 
    Lname = "b_name_last " + tbLName.Text
};

var json = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonString = json.Serialize(application);

string endPoint = token.instance_url + "/services/apexrest/submitApplication/";    
string response = conn.HttpPost(endPoint, json, token);
Literal rLiteral = this.FindControl("resultLiteral") as Literal;

I need the JSON string to output inside of a JSON Object. An example of what I need is below:

"{ \"jsonCreditApplication\" : " +
    "\"gors_descr\" : \"Appliances\", " +
    "\"b_name_first\" : \"Marisol\", " +
    "\"b_name_last\" : \"Testcase\", " +
"}"; 

This hard coded json string is inside of an object. As it stands, the values in the C# object are being outputted into a JSON string, but I'm needing it output into an object so that the Salesforce API will accept the submission.

How can I append or insert the JSON string into an object?

Aleksandr Ivanov
  • 2,778
  • 5
  • 27
  • 35
Mowrite
  • 183
  • 1
  • 2
  • 10
  • http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object?rq=1 ? – stuartd Jan 18 '16 at 19:05
  • for starters make sure that your json string is valid you can actually use this site to convert json string into C# Class http://json2csharp.com/ also look at this link to [convert C# Object into Json](http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4) – MethodMan Jan 18 '16 at 19:08
  • First of all when you serialize `application` you will get JSON that will look like: `{"ProductDescription": "gors_descr Appliances", "Fname": "b_name_first Marisol", ...}`. It doesn't look like JSON you want. – Aleksandr Ivanov Jan 19 '16 at 00:05

5 Answers5

20

To create correct JSON first you need to prepare appropriate model. It can be something like that:

[DataContract]
public class Customer
{
    [DataMember(Name = "gors_descr")]
    public string ProductDescription { get; set; }

    [DataMember(Name = "b_name_first")]
    public string Fname { get; set; }

    [DataMember(Name = "b_name_last")]
    public string Lname { get; set; }
}

To be able to use Data attributes you will need to choose some other JSON serializer. For example DataContractJsonSerializer or Json.NET(I will use it in this example).

Customer customer = new Customer
{
    ProductDescription = tbDescription.Text,
    Fname = tbFName.Text,
    Lname = tbLName.Text
};


string creditApplicationJson = JsonConvert.SerializeObject(
    new
    {
        jsonCreditApplication = customer
    });

So jsonCreditApplication variable will be:

{
  "jsonCreditApplication": {
    "gors_descr": "Appliances",
    "b_name_first": "Marisol",
    "b_name_last": "Testcase"
  }
}
Aleksandr Ivanov
  • 2,778
  • 5
  • 27
  • 35
3
using System; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Linq;

CurrentUTCDateTime yourObject = new CurrentUTCDateTime(); 
JObject json = JObject.Parse(JsonConvert.SerializeObject(yourObject));
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • 3
    Welcome to StackOverflow! Please provide some explanation why do you think your proposed solution might help the OP. – Peter Csala Aug 26 '20 at 12:10
  • 1
    My solution will helpful who want to get json from object as an JsonObject – Md. Foyjul Bary Aug 26 '20 at 12:17
  • Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users with similar issues. – FluffyKitten Aug 27 '20 at 02:20
2

Another way.

using System;
using Newtonsoft.Json;

namespace MyNamepace
{
    public class MyCustomObject
    {
        public MyCustomObject()
        {
        }

        [JsonProperty(PropertyName = "my_int_one")]
        public int MyIntOne { get; set; }

        [JsonProperty(PropertyName = "my_bool_one")]
        public bool MyBoolOne { get; set; }

    }
}

and

        /* using Newtonsoft.Json; */

        MyCustomObject myobj = MyCustomObject();
        myobj.MyIntOne = 123;
        myobj.MyBoolOne = false;

        string jsonString = JsonConvert.SerializeObject(
            myobj,
            Formatting.None,
            new JsonSerializerSettings()
            {
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            });

see

http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonSerializerSettings.htm

My packages.config at the time of writing...though I'm sure future/latest versions will still support it:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
</packages>
granadaCoder
  • 26,328
  • 10
  • 113
  • 146
  • +1 for using Newonsoft solution - Just remember that to use it you need to install its package using the NuGet Package Manager, and (of course) include Newtonsoft.Json at your "using" section – Thomas Hansen Aug 23 '17 at 11:17
  • 1
    Hey. Thanks for feedback. I added the packages.config. The "using" was already there! :) – granadaCoder Aug 23 '17 at 13:22
2

Install Newtonsoft.Json NuGet then decorate Customer class with the requires naming decorations to tell Json serializer how to serialize the customer class fields:

public class Customer
{
    [JsonProperty("gors_descr")]
    public string ProductDescription;
    [JsonProperty("b_name_first")]
    public string Fname;
    [JsonProperty("b_name_last")]
    public string Lname;
}

Next, serialize the object like this:

Customer application = new Customer
        {
            ProductDescription = "Appliances ",
            Fname = "Marisol ",
            Lname = "Testcase "

        };
        var JsonOutput = JsonConvert.SerializeObject(new { jsonCreditApplication = application });

You will get the desired result and the value of JsonOutput will be : "{\"jsonCreditApplication\":{\"gors_descr\":\"Appliances \",\"b_name_first\":\"Marisol \",\"b_name_last\":\"Testcase \"}}"

There are many ways to do this but I believe that this one is the simplest solution.

Zuhair
  • 837
  • 1
  • 8
  • 12
0

You could use something like http://restsharp.org/, which is a c# library for REST. If so, it has a built in serializer for json objects (.addJsonBody()) or you can serialize it yourself and add with

    request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);

Alternatively if you want more control over it you can use

    System.Net.HttpWebRequest()

I've also found https://github.com/ademargomes/JsonRequest, but it's still in development. Be warned that if you use something like RestSharp, it is a canned request so any variation from what they have created as the standard requests (e.g. multipart/form data w/ json or custom headers or even custom authentication) may not work with their library, in which case it's probably better to make your own using HttpWebRequest anyway. Hope that helps!