Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Converting C# Objects into JSON file

Posted on 2016-11-09
7
Medium Priority
?
126 Views
Last Modified: 2016-11-21
I have class in my C# project that looks like this:

class   Book {
    public string Title  { get; set; }
    public string Author  { get; set; }
    public string Publisher  { get; set; }
    public double Price  { get; set; }
}

In my code I have List of Book objects. I need help with C# code that will convert my list of book objects into JSON format and save it into
Text file in the following JSON Format.
I have seen code like the one I have put in the code window, but when I run it I get the error "Self referencing loop detected in for properly "books"
 

List<Book> books = new List<Book>();
var context = new DbContext();
books = context.Books.ToList():
var json = JsonConvert.SeriliazeObject(books)
System.IO.File.WrieAllText(@c: \pathBooks.txt, json);
 

Open in new window



I would like to see my list of Book objects converted into the following JSON format.

{
       
    "Books" : [
                  {
                  "title": "Crime and Punishment",
                  "author": "Feyodo Destoyosky",
                  "Publisher": "Penguin",
                  "Price": "2.50",
                 
                  },
                 
                  {
                  "title": "Jane Eyre",
                  "author": "Charollote Bronte",
                  "Publisher": "O Reilley",
                  "Price": "5.50",
                 
                  },
                 
                 {
                  "title": "Emma",
                  "author": "Jane Austen",
                  "Publisher": "Harper",
                  "Price": "2.50",
                 
                  }              
                 
                  ]
}
0
Comment
Question by:FaheemAhmadGul
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 40

Accepted Solution

by:
Kyle Abrahams earned 2000 total points
ID: 41881384
If you have foreign keys in books that  can be causing the issue.

try adding:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Also you may need the
[DataContract] object for your class.

A sample class I use for serialization:

[Browsable(false)]
[DataContract]
public class GeoIPResponse
{
    // the name in json
    [DataMember(Name = "ip")]
    public string ipAddress { get; set; } //whatever I want to call it in the class.

    [DataMember(Name = "country_code")]
    public string country_code { get; set; }
    
    [DataMember(Name = "country_name")]
    public string country_name { get; set; }

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

    [DataMember(Name = "region_name")]
    public string region_name { get; set; }
    
    [DataMember(Name = "city")]
    public string city { get; set; }

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

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

    [DataMember(Name = "latitude")]
    public float? latitude { get; set; }

    [DataMember(Name = "longitude")]
    public float? longitude {get; set;}

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

Open in new window

0
 
LVL 1

Author Comment

by:FaheemAhmadGul
ID: 41881610
Many thanks for your comment. It has helped. I actually had a foreign key also in the Book class which was the source of the problem, as you point out. I have been able to get around the problem after you pointed it out. Before I close the question, please let me know where in my project code should I add the following line that you have suggested:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
0
 
LVL 1

Author Comment

by:FaheemAhmadGul
ID: 41883343
Many thanks for your help. Greatly appreciated.
0
Survive A High-Traffic Event with Percona

Your application or website rely on your database to deliver information about products and services to your customers. You can’t afford to have your database lose performance, lose availability or become unresponsive – even for just a few minutes.

 
LVL 82

Expert Comment

by:leakim971
ID: 41895256
where in my project code should I add the following line that you have suggested:

in your Global.asax file inside the Application_Start function

Don't forget to close the question, no points for my comment, I don't deserve any points here.
0
 
LVL 1

Author Comment

by:FaheemAhmadGul
ID: 41896879
I accepted Kyle Abrahams solution as the best solution, the very day it was suggested and in my mind had closed the question, but only now realised it had not been closed properly. Actually what I am finding is that the experts exchange user interface has become unnecessarily complicated and convoluted. So much stuff unrelated to the task is being shown at the same time, that options related to what you are actually doing become extremely difficult. Now I have a 27 inch monitor on which I am typing this comment. I have already ticked the best solution box for the solution Kyle Abrahams  posted and I am seeing all kind of crap on my screen, but nowhere is there the option to close the question.
And when I scroll down on the screen, I see black footer with Membership and About us stuff, but still no button to close the solution or accept the solution.
And yes, after I scrolled down and scrolled up then a popup emerged from the bottom where the footer was with Best Solution and o assisted solution selected.
Perhaps Experts Exchange have forgotten the KISS principle.
0
 
LVL 1

Author Closing Comment

by:FaheemAhmadGul
ID: 41896880
I accepted Kyle Abrahams solution as the best solution, the very day it was suggested and in my mind had closed the question, but only now realised it had not been closed properly. Actually what I am finding is that the experts exchange user interface has become unnecessarily complicated and convoluted. So much stuff unrelated to the task is being shown at the same time, that options related to what you are actually doing become extremely difficult. Now I have a 27 inch monitor on which I am typing this comment. I have already ticked the best solution box for the solution Kyle Abrahams  posted and I am seeing all kind of crap on my screen, but nowhere is there the option to close the question.
And when I scroll down on the screen, I see black footer with Membership and About us stuff, but still no button to close the solution or accept the solution.
And yes, after I scrolled down and scrolled up then a popup emerged from the bottom where the footer was with Best Solution and o assisted solution selected and it was still not clear what to do next.
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 41896905
No issues or problems.  I would have closed it once I was able to.  You can use the contact us to provide feedback to EE.
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question