Solved

Converting C# Objects into JSON file

Posted on 2016-11-09
7
37 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 39

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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
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 39

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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

We will take a look at the d3.js library for visualizations.  I will provide a walkthrough of a short bar graph example as well as introduce you to the d3.js API.  We also will explore links of other examples and further information regarding SVG's.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

707 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

18 Experts available now in Live!

Get 1:1 Help Now