SimpleJSON and C# How to write json from multiple objects ?

Hi ! I’m trying to do those things :

1- read a json

2- select some data inside the json

3- generate a new json

I’m stuck at 3) I try to generate a json from objects created by a for loop. Also if you have any documentation about simplejson it would be appreciated because i’m a bit lost.

public class CollectCards : MonoBehaviour
{
    public string set;
    public string Rid;
    public string Rname;
    public string Rset;

    // Use this for initialization
    void Start ()
    {
        string str = Read ();
        JSONNode cardData = JSON.Parse (str);
        string[] setlist = new string[] {
            "Basic",
            "Advanced",
            "Expert"
        };
        for (int j=0; j<setlist.Length; j++) {
            set = setlist [j];
            string verif = "green";
            for (int i =0; i<cardData[set].Count; i++) {
            if (cardData [set]  *[verif] != null) {*

_ Rname = cardData [set] [“name”].Value;_
* }*
* } else*
Rname = “none”;
Rid = cardData [set] [“id”].Value;
Rset = setlist [j];
Card carte = new Card (Rid, Rname,Rset);
// I’M STUCK HERE, The idea is to have “Add carte to Json File”//
}
}
}
string Read()
{
StreamReader sr = new StreamReader (Application.dataPath + “/Resources/Cards.json”);
string content = sr.ReadToEnd ();
sr.Close();
return content;
}
}

public class Card {
public string id;
public string name;
public string cardset;

public Card(string id, string name, string cardset)
{
this.id = id;
this.name = name;
this.cardset=cardset;
}
}
Thank you for your help !

You probably want to put the saving and loading code into the Card class itself. You also should use some kind of CardSet class to actually manage your cards:

public class CardSet
{
    public string name;
    public List<Card> cards = new List<Card>();
    public CardSet(string aName)
    {
        name = aName;
    }

    public CardSet(string aName, JSONNode aNode)
    {
        name = aName;
        for(int i = 0; i < aNode.Count; i++)
        {
            cards.Add(new Card(aNode*, this));*

}
}
public JSONNode SaveToJSON()
{
JSONNode node = new JSONArray();
for(int i = 0; i < cards.Count; i++)
node.Add(cards*.SaveToJSON());*
return node;
}
}

public class Card
{
public string id;
public string name;
public string cardset;
public Card(string id, string name, string cardset)
{
this.id = id;
this.name = name;
this.cardset = cardset;
}
public Card(JSONNode aNode, CardSet aCardSet)
{
id = aNode[“id”].Value;
if (aNode[“green”] != null)
name = aNode[“name”].Value;
else
name = “none”;
cardset = aCardSet.name;
}
public JSONNode SaveToJSON()
{
JSONNode node = new JSONClass();
node[“id”] = id;
node[“name”] = name;
return node;
}
}
To load your cards you can simply do:
string[] setlist = new string[] {
“Basic”,
“Advanced”,
“Expert”
};

List sets = new List();
void LoadCards()
{
string str = Read ();
JSONNode cardData = JSON.Parse (str);
for (int j = 0; j < setlist.Length; j++) {
sets.Add(new CardSet(setlist[j], cardData[setlist[j]]));
}
}

void SaveCards()
{
JSONNode cardData = new JSONClass();
for (int j = 0; j < sets.Count; j++) {
cardData[sets_.name] = sets*.SaveToJSON();
}
string json = cardData.ToString();
SaveTheStringSomewhere(json);
}*

That’s just an example. SimpleJSON was never ment to be a serializer. It’s just a framework that simplifies working with JSON data.
Your “green” check was a bit confusing to me. Maybe you wanted to do something else. I just copied it from your code ^^.
To add new cards you can simply use one of your CardSet classes and add a new card:
CardSet set = sets[0];
set.cards.Add(new Card(“SomeID”, “CarName”, set.name));
When you call “SaveCards()” the new cards will be saved as well._

Hi everybody. My case:

I get a WWW response of my server, and its string is an Array with the JSON data of the results of gameplays.

I needed to parse all the data and I did these steps:

0.- Install the package of http://wiki.unity3d.com/index.php/SimpleJSON, and write at the top of my script the “using SimpleJSON;” statement.

1.- Create a Serializable Class that will act as a model to hold the data of each result:

  [System.Serializable]
    public class ResultsInfo
    {
    	//example of data:
    	//{"id_challenge":"1","game":"buzkanoid","prize":"0.20","user1":"Soldeplata Sakettos Candela","score_u1":"1500",
    	//"start_time_u1":"2016-03-19 12:20:08","end_time_u1":"2016-03-19 12:20:20","data_u1":null,"user2":null,"score_u2":"0",
    	//"start_time_u2":null,"end_time_u2":null,"data_u2":null,"winner":null,"status":"pending"}
    	public string id_challenge, prize, user1, score_u1, start_time_u1, data_u1, img_u1, img_u2, user2, end_time_u2, data_u2, winner, status;
    	
    }
  1. Fetch the data with a WWW function and store it in a JSON node:

    public List resInfo = new List ();

     //This coroutine is called after connecting with the www method "startCoroutine(RetrieveResultsCo (new WWW (url))"
        	IEnumerator RetrieveResultsCo (WWW w)
        	{
        		yield return w;
        
        		if (w.error == null) {
        		
        			var N = JSON.Parse (w.text); //this is the node
        			//add into the list the result of matches of the player
        			for (int i = 0; i < N.AsArray.Count ; i++) {
        				resInfo.Add (JsonUtility.FromJson<ResultsInfo> (N *.ToString ()));*
    
  •  	}*
    

//just do something with the list :smiley:

  •  	foreach (ResultsInfo result in resInfo) {*
    
  •  		print (result.score_u1);*
    
  •  	}*
    
  •  }*
    
  • }*

sorry for the formatting, I am trying to solve it, but it does not work as expected for me :frowning: