Solved

Converting C# Objects into JSON file

Posted on 2016-11-09
7
118 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 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
 
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

627 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