0

I'm trying to understand Json. Easy object and string - it's clear. What about objects like

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using State;
using System.IO;

namespace JSON
{
            [Serializable]]
            class Top{
             public int I = 0;
             public List<Q> lst = new List<Q>();
             public Top() { lst.Add(new Q()); }
            }

            [Serializable]
            class Q {
              int i1 = 100500;
              string s1 = "abrakadabra";
              List<A> aList = new List<A>();
              public Q() { aList.Add(new A()); }
            }

            [Serializable]
            class A {
              string text = "secret will of my Dad";
            }

    class Program
    {
        static void Main(string[] args)
        {
            Top exam = new Top();
            string DataString = JsonConvert.SerializeObject(exam);
            JsonSerializer serializer = new JsonSerializer();
            TextWriter tw = new StreamWriter("test.txt"); 
            serializer.Serialize(tw, exam);
            tw.Flush();
            tw.Close();
            sw.Close();
        }
    }
}

Would it be able to enline in Json string such structure of a C# object, and then, to build it inside Java code with the same field names and types?

If "yes" then why do I have {"I":0,"lst":[{}]} as the result in test.txt?

  • What does XML have to do with Json? As to your question, sure you can serialize `Top` to Json in c# and deserialize in Java. – Oleg Sep 23 '17 at 05:18
  • Top only? What about lst value, will it be with Q and the Q with A? –  Sep 23 '17 at 06:07
  • Yes, it's entirely up to you, or to the framework you use. – Oleg Sep 23 '17 at 06:09
  • pls, see my update –  Sep 23 '17 at 06:18
  • Try to add `[JsonProperty("something")]` to stuff, like I said it's up to you and the framework, if the framework you use can't handle it, you might have to use a different one or do more yourself. You should remove the `java` tag and add `json.net` somebody who knows it, will help you. – Oleg Sep 23 '17 at 06:40
  • 2
    The fields of `Q` are not serialized because they are not public. Make them public, or mark them with [`[JsonProperty]`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_JsonProperty.htm) as explained in [Json.net serialize specific private field](https://stackoverflow.com/q/32008869). – dbc Sep 23 '17 at 09:50
  • Possible duplicate of [Private setters in Json.Net](https://stackoverflow.com/questions/4066947/private-setters-in-json-net) – shA.t Sep 23 '17 at 09:54

0 Answers0