1

I am using web api and I need to saving json objects to my database. I will get the screen size, color, ... and save to database.

{ "height": 1536, "width": 2048, "color": "#114521" }

But I do not want to create C# class for this data. I want to create a class named settings:

public class Settings{ 
   public string Username {get;set;}
   public string Data {get;set;}  // This will be json settings data
}

But I will get back this as json object.

I am creating a new settings C# instance:

public Settings Get(){
   var settings = new Settings{
    Username="myname",
    Data="{ \"height\": 1536, \"width\": 2048, \"color\": \"#114521\" }"
   };
   return settings;
 }

But Data is going to client as text, not json object. (I will save Data to database as raw json.)

barteloma
  • 6,403
  • 14
  • 79
  • 173
  • Just to confirm -- are you serializing `Settings` to and from your database, or are you just using it as a DTO to return values from web API? – dbc Feb 04 '17 at 15:38
  • Does this answer your question? [How to Deserialize json to object so nested json will convert into JSON list instead of object](http://stackoverflow.com/a/40539360/3744182). – dbc Feb 04 '17 at 15:43
  • Sounds like you might have enabled use of `DataContractJsonSerializer`. See https://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_media_type_formatter and https://stackoverflow.com/questions/20371040/am-i-using-datacontractjsonserializer-or-the-json-net-one-in-my-web-api-2. – dbc Feb 04 '17 at 16:14

2 Answers2

0

In the example provided, Json is a string, it is not an object until it is deserialized. The string contained in Settings.Data can be passed to your Insert query. You can have a column to store the entire Json string. if your database is SQL Server, the varchar data type has a maxlength of 8000, or you can use varchar(max) which is almost unlimited.

So to store your json string in the database:

  1. Create a column (if not already existing) to store the data
  2. Create an SQL insert statement to insert the value into the database. Such as:

    INSERT INTO MyTable (UserName, JsonColumnName) VALUES (@userName, @JsonString)
    
  3. Pass the value from Settings.Data to your insert statement or SQLParameter object, depending on the format your application is interacting with your database.

To get the Json value from the database:

  1. Create a select state to find the correct json string, based on user name, or whatever unique id is used to identify the json string,
  2. Retrieve the json string from the query results.
SteveD
  • 819
  • 7
  • 13
0

Does not matter , it is not appear as Json string. when serialize to json in client side, it will convert as object.

var obj = JSON.parse('{ \"height\": 1536, \"width\": 2048, \"color\": \"#114521\" }');