Solved

Converting C# Objects into JSON file

Posted on 2016-11-09
7
66 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
  • 4
  • 2
7 Comments
 
LVL 40

Accepted Solution

by:
Kyle Abrahams earned 500 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
 

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
 

Author Comment

by:FaheemAhmadGul
ID: 41883343
Many thanks for your help. Greatly appreciated.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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
 

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
 

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

895 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now