Solved

Converting C# Objects into JSON file

Posted on 2016-11-09
7
100 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
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
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

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.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

751 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