• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 548
  • Last Modified:

converting a dataset to JSON using json.net

This is a somewhat related question to my previous thread found here.

My next step that I want to accomplish is to take a dataset and convert it's contents into a JSON object, where I can then "loop" through each object and manipulate the data. being extremely new to .NET, I'm sure I'm missing a piece or two in my solution :)

I'm able to fill up my data set with nor problem, and verified this through the dataset visualizer. The code I'm using to convert my dataset is:

        private PendingOrders getOrdersToProcess(DAL_Class dbHelper)
        {
            var json = JsonConvert.SerializeObject(dbHelper.getPendingOrders(_mode));
            return JsonConvert.DeserializeObject<PendingOrders>(json);

        }

Open in new window


and my PendingOrders class:

    public class PendingOrders
    {
        public int orderID                          { get; set; }
        public int dataID                           { get; set; }
        public string recipientEmail                { get; set; }
        public string instructions                  { get; set; }
        public DateTime needBy                      { get; set; }
        public string recipientName                 { get; set; }
        public string company                       { get; set; }
        public string recipientPhone                { get; set; }
        public string address1                      { get; set; }
        public string address2                      { get; set; }
        public string City                          { get; set; }
        public string StateProv                     { get; set; }
        public string Country                       { get; set; }
        public string PostalCode                    { get; set; }
        public string CCG_Sku                       { get; set; }
        public int quantity                         { get; set; }
    }

Open in new window


the dbHelper.getPendingOrders() function fills up the dataset and returns it. if I run the following code:

var po = new PendingOrders();
po = getOrdersToProcess(dbHelper);

Open in new window


none of my data is in the po object, everything is null.

So I guess my first question is why? the JSON being returned is multiple objects (each row is it's own object). Do I need to create some kind of collection of objects here? If so, what's the best way to do that?

my second question is once I have this data converted over to some kind of (collection of) object(s), how can I loop through it and read each individual object?
0
Big Monty
Asked:
Big Monty
  • 6
  • 4
  • 2
3 Solutions
 
käµfm³d 👽Commented:
What is the return type of getPendingOrders?
0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Author Commented:
It returns a data set
0
 
käµfm³d 👽Commented:
Then that's your problem:  You cannot mix types--generally--when serializing. A DataSet is not a PendingOrders, so it's not going to get serizlized into one by the serializer. You'll need to perform some mapping of your DataSet into a collection of PendingOrders.
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Big MontySenior Web Developer / CEO of ExchangeTree.org Author Commented:
the line:

var json = JsonConvert.SerializeObject(dbHelper.getPendingOrders(_mode));

creates a string of all of the json data. I thought when I called the Deserialize function, it did the mapping for me...

Is there a better, more efficient way to do this? My end goal is to take some data from the database and put it in a JSON object so that I can use it at different points in my program
0
 
käµfm³d 👽Commented:
creates a string of all of the json data. I thought when I called the Deserialize function
This line:

var json = JsonConvert.SerializeObject(dbHelper.getPendingOrders(_mode));

...does do that. But this line:

JsonConvert.DeserializeObject<PendingOrders>(json);

...does not do what you intend it to do. If getPendingOrders returned a PendingOrders object, then that line would work. Unfortunately, you said that it returns a DataSet. DataSet != PendingOrders. If your goal is to transmit data across the wire, then honestly I would ditch the DataSet, and just populate a collection of (what I shall call) your entity class (i.e. PendingOrders).

e.g.

public class DAL_Class 
{
    public IEnumerable<PendingOrders> getPendingOrders()
    {
        List<PendingOrders> orders = new List<PendingOrders>();
        
        using (SqlConnection con = new SqlConnection("your connection string"))
        {
            using (Sqlcommand cmd = new SqlCommand("your query", con))
            {
                try
                {
                    SqlDataReader reader;
                    
                    con.Open();
                    reader = cmd.ExecuteReader();
                    
                    while (reader.Read())
                    {
                        PendingOrders order = new PendingOrders();
                        
                        order.orderID = (int)reader["orderId column name"];
                        order.dateID = (int)reader["dateId column name"];
                        // etc.
                        
                        orders.Add(order);
                    }
                }
                catch (SqlException)
                {
                    // Handle exception
                }
            }
        }
        
        return orders;
    }
}

Open in new window



Side Note: Not that there's anything wrong with it from a functional point of view, but the convention in .NET is to use Pascal-style naming for classes, methods, and properties. Camel-casing is reserved for variable/field names. As I said, it's not broken, but don't be surprised if someone else mentions it  ; )
0
 
Walter PadrónCommented:
IMHO if you are moving data between layers in your own application you better stick with a collection so you don't need to serialize and deserialize;   json is more suitable to move data between different platforms or over internet.

You can iterate over a collection with the foreach statement
0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Author Commented:
@Kaufmed

thank you for that bit of code, I'm currently tying it into my project and getting it to work. I guess that was the answer to my question "what is the best collection to use when I want to take data from the database and keep in memory for later use?" what I'm ultimately trying to do is take a list of orders from the database with a status of pending, then call a 3rd party web service that returns the number of items in stock for each item ordered. as long as the number ordered is less than what's in stock, I'll call another web service and place the order

@WP

Agreed. It was a more of a learning exercise that I started off that way than anything else.
0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Author Commented:
By the way, my code for calling the new getPendingOrders() function (I'm just so used to camel case!) is below. Does that look correct?

IEnumerable<PendingOrders> PendingOrders = new List<PendingOrders>();
PendingOrders = dbHelper.getPendingOrders(_mode);

Open in new window

0
 
käµfm³d 👽Commented:
I don't see any errors. From a stylistic point of view:

There's no reason to initialize a new list as your first operation. The very next line assigns the result of the method call to the list, so the first initialization is really pointless. My suggestion is to collapse it into a single line:
IEnumerable<PendingOrders> PendingOrders = dbHelper.getPendingOrders(_mode);
It might be confusing to have a variable name that is the same name as a class--and in some cases it's a compiler error; surprised you're not seeing such. This is where the camel casing would come into play
IEnumerable<PendingOrders> pendingOrders = dbHelper.getPendingOrders(_mode);

Also, IMO your class name should be singular:  PendingOrder. A collection of those classes would be plural.
0
 
Walter PadrónCommented:
Ahh, OK.  I suggest learn LINQ and/or EF next.

You can do something like this
var  context = new DatabaseContext();
var results = from o in context.Orders
                         where o.OrderID < 100
                         select ConvertToPendingOrders(o);

Open in new window

0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Author Commented:
thanks to both experts for clear concise answers and explanations!
0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Author Commented:
I've added another question if you have any time to look at it:

http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_28579056.html
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

  • 6
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now