Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by sachou · Jul 24, 2015 at 10:46 AM · c#deserialize

Deserialize Json array with JsonFx in unity

Hello everyone, I dev an application with Json data, I'm using JsonFx and I have a Json like this : I use unity 4.5.6

 [
     {
         "id": "7", // all string value
         "lastname": "Meurot Desterhx",
         "firstname": "Ludovic",
         "phone": "",
         "mobile": "",
         "email": "destylia@hotmail.fr",
         "password": "5",
         "date_of_birth": "0000-00-00",
         "facebook_id": "",
         "facebook_link": "",
         "facebook_locale": "",
         "online": "1",
         "boutiques": {
             "fruity": 1, //int value
             "minicar": 2 // int value
         }
     }
 ]


So, I have two classes.

1 : UserClass.

2 : siteWebClass.

see the code: userClass

    public class userClass  
 {
 
     public string id {get;set;}
     public string email { get; set; }
     public string gameId { get; set; }
     public string userType {get;set;}
     public string connexionDate { get; set; }
     public string fbId { get; set; }
     public string fbEmail { get; set; }
     public string fbFirst_Name { get; set; }
     public string fbLast_Name { get; set; }
     public string fbName { get; set; }
     public string fbLink { get; set;}
     public string fbLocal { get; set; }
     public float Credit{get;set;}
     public string Ctype { get; set; }
     public List<webSiteClass> boutiques { get; set; }
     public List<userClass>userInfos;
     private static userClass instance;
 
     public userClass()
     {
 
     }
 
     public static userClass Instance
     {
         get
         {
             if (instance == null)
             {
                 instance = new userClass();
             }
             return instance;
 
         }
     }
     public userClass ( string _id )
     {
         id = _id;
         userInfos = new List<userClass> ( );
     }
 
     public userClass ( string _id, 
                       string _email, 
                       string _userType, 
                       string _connexionDate, 
                       string _fbId, 
                       string _fbEmail, 
                       string _fbFirst_Name,
                       string _fbLast_Name, 
                       string _fbName, 
                       string _fbLink, 
                       string _fbLocal,
                       string _Ctype,
                       List<webSiteClass> _boutiques,
                       float _Credit )
     {
         id = _id;
         email = _email;
         userType =_userType;
         connexionDate = _connexionDate;
         Credit = _Credit;
         fbId = _fbId;
         fbEmail = _fbEmail;
         fbFirst_Name = _fbFirst_Name;
         fbLast_Name = _fbLast_Name;
         fbName = _fbName;
         fbLink = _fbLink;
         fbLocal = _fbLocal;
         Ctype = _Ctype;
         for (int i = 0; i < boutiques.Count; i++) 
         {
             boutiques[i].websiteId = _boutiques[i].websiteId;
             boutiques[i].logo = _boutiques[i].logo;
             boutiques[i].name = _boutiques[i].name;
             boutiques[i].fruity = _boutiques[i].fruity;
             boutiques[i].minicar = _boutiques[i].minicar;
         }
         Credit = _Credit;
         userInfos = new List<userClass> ( );
     }

siteWebClass:

 using JsonFx.Json;
 using JsonFx;
 
 
 public class webSiteClass : MonoBehaviour
 {
     public int websiteId { get; set; }
     public string logo { get; set; }
     public string name { get; set; }
     public int fruity { get; set; }
     public int minicar { get; set; }
 
 
 
     public webSiteClass()
     {
 
     }
 
     public webSiteClass( int _websiteId,
                          string _logo, 
                          string _name, 
                          int _fruity, 
                          int _minicar)
     {
 
         websiteId = _websiteId;
         logo = _logo;
         name = _name;
         fruity = _fruity;
         minicar = _minicar;
 
     }
 }


So I deserialize the Json, it works but when I check the List "boutique" is empty. See my Deserialize code:

     public IEnumerator Connect ( string _eMail , string _Mdp, string _gameName, string _Ctype )
     {
         WWWForm form = new WWWForm ( ); // variable de type WWWForm, une "class aide" pour generer des données depuis un server web sous forme de formulaire (utilisateur, mdp etc...)
         eMail = _eMail;
         Mdp = _Mdp;
         gameName = _gameName;
         Ctype = _Ctype;
         form.AddField ( "email" , _eMail ); // on ajoute _eMail au formulaire
         form.AddField ( "password" , _Mdp );// on ajoute _Mdp au formulaire
         form.AddField ("gameName", "");
 //      form.AddField ("cType", _Ctype);
 
         WWW www = new WWW ( urlConnection , form );/* Variable de type WWW qui prend en paramettre un url en local, lien serveur, ou ftp. Il peut avoir comme ici en plus de l'url un formulaire. 
                                                     * Ici nous avons la variable "urlConnexion et le formulaire form) */
 
 
         yield return www;/* une fois l'url envoyer il est retourné sous un format qui est le Json, qui une chaine de caractère avec une syntaxe spécifique.
                             Le Json contients les données de l'utilisateur son Nom d'utilisateur son mot de passe */
 
         Debug.Log (www.text);
 
         if ( www.error == null )// si le json n'est pas éronné
         {
             string[] UrlSplit = www.text.Split('\\'); // le Json renvoyer contient des '\' nous les enlevons pour pouvoir le deserialiser 
             string concat = "";
             for (int i = 0; i < UrlSplit.Length; i++) 
             {
                 concat+=UrlSplit[i];
             }
             Debug.Log(concat);
             userClass[] userJson = JsonFx.Json.JsonReader.Deserialize<userClass[ ]> ( www.text); // on decoupe le format json et on met ses morceaux dans une liste qui ici est une liste de type userClass 
 
             //le json contenait les Id de l'utilisateur ainsi que son mot de passe  et d'autre paramettres, nous remplissons la liste.
 
             for (int i = 0; i < userJson.Length; i++) 
             {
                 Debug.Log(userJson[i].id);
                 Debug.Log(userJson[i].email);
                 Debug.Log(userJson[i].boutiques);
                 Debug.Log(userJson[i].boutiques.Count);
                 foreach (webSiteClass item in userJson[i].boutiques)
                 {
 
                     Debug.Log("item : " +item);
 
                 }
             }
 
             user.id = userJson [ 0 ].id; 
             user.email = userJson [ 0 ].email;
             user.userType = userJson [ 0 ].userType;
             user.connexionDate = userJson[ 0 ].connexionDate;
             user.Credit = userJson[ 0 ].Credit;
 
 
 
 
             if ( eMail == userJson [ 0 ].email && user.Ctype == userJson[0].Ctype)// si eMail que l'utilisateur a taper est le meme que celui dans la BDD
             {
                 Debug.LogWarning ( "good" );
                 winChoose = true;
             }
 
         }
         else
         {
             Debug.LogError ( "wrong" ); // l'utilisateur a écrit un mauvais login ou un mauvais mdp.
             feedBackError = "<color=red>" + "Mauvais login ou Mot de passe !" + "</color>";
             yield return new WaitForSeconds ( 2f );
             feedBackError = "";
         }
     }







see my debug log:

Debug.Log(userJson[i].boutiques); = System.Collections.Generic.List`1[webSiteClass]

Debug.Log(userJson[i].boutiques.Count); = 0

Any idea ? I'm Lost, thank for help and have you nice day.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image sachou · Jul 24, 2015 at 12:34 PM 0
Share

Any idea ?

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by mckamey · Jul 25, 2015 at 04:37 PM

There are a few things wrong here but the two important issues:

First, your JSON doesn't match your model. Specficially the botiques field contains an object rather than an array (line 15):

 "boutiques": {
      "fruity": 1, //int value
      "minicar": 2 // int value
  }

Should be:

 "boutiques": [
     {
          "fruity": 1, //int value
          "minicar": 2 // int value
     }
 ]

That is why it fails to deserialize. Type mismatch.

The next biggest issue is in your copy constructor. You're going to get a NullReferenceException if you pass in a list of boutiques (line 73):

     for (int i = 0; i < boutiques.Count; i++)  // <= boutiques is null here
      {
          boutiques[i].websiteId = _boutiques[i].websiteId;  // <= boutiques[i] is null here
          boutiques[i].logo = _boutiques[i].logo;
          boutiques[i].name = _boutiques[i].name;
          boutiques[i].fruity = _boutiques[i].fruity;
          boutiques[i].minicar = _boutiques[i].minicar;
      }

You need to instantiate a new webSiteClass for each that you are copying. Also you probably want to ensure that the passed in list isn't null. Something like:

 if (_boutiques != null) {
     boutiques = new List<webSiteClass>();
     for (webSiteClass b in _boutiques) 
     {
         boutiques.add(
             new webSiteClass(b.websiteId, b.logo, b.name, b.fruity, b.minicar);
     }
 }

There a bunch of little issues like that in this code. Also if you are going to use an item in a List multiple times (e.g., _boutiques[i]) then it makes sense to pull that value to a local temporary variable so you aren't traversing the list over and over again (i.e., [i] is not free):

 webSiteClass b = _boutiques[i];
 ... = b.webSiteId;
 ... = b.logo;
 ... = b.name; // etc.

Finally, unless C# naming conventions are different when using Unity (I've never used Unity but I wrote JsonFx so I'm familiar with C#), then you have a lot of things going on. Typically classes, methods and properties are PascalCase (i.e., start with a capital letter) and fields are camelCase (i.e., start with a lowercase letter). Local variables and parameters typically do not start with an underscore (`'_'`). If you need to differentiate between the class member and the local variable then you use this.myFieldName.

Like I said I've never used Unity so take some of that with a grain of salt. Sometimes those kinds of rules get modified in mixed environments.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image sachou · Jul 30, 2015 at 02:43 PM 0
Share

I found the solution my colleague who takes care to send me the Json, was amended . I could do my builder properly and deserialize the json is well :

 [
     {
         "id": "7",
         "lastname": "",
         "firstname": "",
         "phone": "",
         "mobile": "",
         "email": "",
         "password": "",
         "date_of_birth": "0000-00-00",
         "facebook_id": "",
         "facebook_link": "",
         "facebook_locale": "",
         "online": "1",
         "boutiques": [
             {
                 "id": "1",
                 "name": "fruity",
                 "logo": "/topten/webroot/upload/images/Logo/Fruity/1438111158_dooffy_ikony_christmas_0004_apple.png"
             },
             {
                 "id": "2",
                 "name": "$$anonymous$$icar",
                 "logo": "/topten/webroot/upload/images/Logo/$$anonymous$$inicar/1438110560_Old-Car-2.png"
             },
             {
                 "id": "3",
                 "name": "flower",
                 "logo": "/topten/webroot/upload/images/Logo/Burger/1437417702_licq.png"
             }
         ]
     }
 ]


Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Making a bubble level (not a game but work tool) 1 Answer

An OS design issue: File types associated with their appropriate programs 1 Answer

how can i deserialize xml to vector4 List?? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges