Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello,
I cant able to read JSON object that I get in Web service and cant able to read contain data.

Here is my Web service..

 [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
    public string updateUserInfo(object InputData)
    {

       /*here I want to read object 'InputData'
         and I want to save data in database*/

SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

        con.Open();
       //SqlCommand cmd = new SqlCommand("getUserById ", con);
        //cmd.CommandType = CommandType.StoredProcedure;
        //cmd.Parameters.Add("@userId", SqlDbType.VarChar).Value = InputeData;
        //cmd.Parameters.Add("@userId", SqlDbType.VarChar).Value = fName;
        //cmd.Parameters.Add("@userId", SqlDbType.VarChar).Value = lName;
        //cmd.Parameters.Add("@userId", SqlDbType.VarChar).Value = email;
        //cmd.Parameters.Add("@userId", SqlDbType.Date).Value = DOB;


What I have tried:

I get data from a remote location using ajax, Ext JS.
I want to get InputeData boject contains.

The InputeData object Contain JSON Data as bellow.

{"UserInfo":{"userId":"vikashire","fname":"vikas","lname":"hire","email":"vikashire@yahoo.com","gender":true,"bloodGroup":"A RhD positive (A+)","hieght":""}}
Posted
Updated 3-Jan-17 2:05am
Comments
Richard MacCutchan 3-Jan-17 4:33am    
where is the code that reads/parses the JSON?

I usually cheat somewhat with those.
When I read a JSON source, I want to inject it inside a database.

At first, I tried to decode it properly and so on.
Was messy and not optimized.
So I went the brute hard-force way : BULK INSERT from the JSON flux to a table, then I have a stored procedure that grabs data from that input table (where everything gets injected from the JSON as String) and the procedure does the conversions and tests using an UPDATE/INSERT.

JSON -> Bulk Insert to TEMP_BLAH
Call (stored_procedure_blah) : moves from TEMP_BLAH to BLAH
doing either an INSERT if data not present, or an UPDATE is already present.

It's fast. It puts a temporary table where the JSON data gets dropped,
so the internal table with converted data is kept safe for content.

The C# code itself is simple :
create a
HttpWebRequest
object
You inject inside of it the JSON URL like this :

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);


Url here contains a string with the JSON URL. Then :

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    json = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (WebException ex)
            {
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    Console.WriteLine(reader.ReadToEnd());
                    return some_errror_value;
                }
            }


(this is code written by hand and not tested but you get the idea of how to do it)

json is a string. It now contains the JSON data.

I then use an XmlDocument to Deserialize the JSON :

System.Xml.XmlDocument xml = JsonConvert.DeserializeXmlNode(json, TableName);


TableName is a variable that contains the name of the table I want to inject the contents into.

DataSet dataSet = new DataSet();

dataSet.ReadXml(XmlReader.Create(new StringReader(xml.InnerXml)), XmlReadMode.InferSchema);


Data goes from Xml to DataSet

Then I open a connection to the SQL Database and inject the data I have as a BULK INSERT :

SqlConnection conn = new SqlConnection(ConnectionString);
                conn.Open();


ConnectionString
contains your SQL usual connection string

foreach(DataTable dt in dataSet.Tables)
                {
                    string TableName = "[IMPORT_" + dt.TableName.Replace('{', ' ').Replace('}', ' ') + "]";
                    ExecuteNonQuery(conn, String.Format("DROP TABLE {0}", TableName));
                    SqlBulkCopy bulk = new SqlBulkCopy(conn);
                    bulk.DestinationTableName = TableName;
                    bulk.WriteToServer(dt);
                }


static private bool ExecuteNonQuery(SqlConnection conn, string sql)
        {
            try
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    Debug.WriteLine(sql);
                    cmd.CommandText = sql; cmd.ExecuteNonQuery();
                }
                Debug.WriteLine("ok");
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
        }


And this does the BULK INSERT work.

I wrote all of this as I recall it. You might have to do a little work for a complete solution, but gives you an idea of how I do it.

It's brutal but it works very nicely. I have a dozen of JSON sources, for each I grab the JSON and inject into an IMPORT_blabla table using BULK INSERT and dropping the existing table. You can do a TRUNCATE instead of a DROP if you prefer.

Then, you have your data in IMPORT_* tables and a stored procedure will do the INSERT/UPDATE work as needed.
 
Share this answer
 
Comments
Vikas Hire 3-Jan-17 5:50am    
Thank You..
Thank you GilBouFR..

Actually I found the solution for my problem.

I get import in my code.
using Newtonsoft.Json;
And get Deserialize Object by using below code.

var jsonResult = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(InputData);


And I got What I want..

string userId =jsonResult["userId"];
       string fname = jsonResult["fname"];
       string lname = jsonResult["lname"];
       string email = jsonResult["email"];
       string DOB = jsonResult["DOB"];
       bool gender = jsonResult["gender"];
       string bloodGroup = jsonResult["bloodGroup"];
       string hieght = jsonResult["hieght"];

       SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

       con.Open();
       SqlCommand cmd = new SqlCommand("UpdateUserInfo ", con);
       cmd.CommandType = CommandType.StoredProcedure;
       cmd.Parameters.Add("@userId", SqlDbType.VarChar).Value = userId;
       cmd.Parameters.Add("@firstName", SqlDbType.VarChar).Value = fname;
 
Share this answer
 
Yup. On my case, I had about a dozen JSON sources, with no explanation for the contents besides "mmm grab from column X and Y from this JSON and you'll also need Z from that another one".

If you got a JSON schema it becomes much more easier :-)
 
Share this answer
 
Comments
Vikas Hire 3-Jan-17 8:07am    
ok.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900