Search Unity

How to convert the list containing different datatypes into a single string?

Discussion in 'Scripting' started by zyonneo, Feb 21, 2019.

  1. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    I have list containing float ,int and string values.How to convert all those values into a single string.

    Code (CSharp):
    1.  
    2.    List<HandleValues> SaveValues = new List<HandleValues>();
    3.    SaveValues.Add(new HandleValues(id,modname,Positionx,Positiony,Positionz,Rotationw,Rotationx,Rotationy,Rotationz));
    4.  
    5. //How to get all those values inside the SaveValues list as a single string so that I can convert it into JSON
    6. string Alldetails=  SaveValues.(???????)
    7.  
    8.  
    9.  
    10. //DataHandler Class
    11.  
    12. using System.Collections;
    13. using System.Collections.Generic;
    14. [System.Serializable]
    15. public class HandleValues
    16. {
    17.      public int Id  { set; get; }
    18.      public string Modelname { set; get; }
    19.      public float Posx { set; get; }
    20.      public float Posy { set; get; }
    21.      public float Posz { set; get; }
    22.      public float Rotw { set; get; }
    23.      public float Rotx { set; get; }
    24.      public float Roty { set; get; }
    25.      public float Rotz { set; get; }
    26.      public HandleValues(int id,string modelname,float posx,float posy,float posz,float rotw,float rotx,float roty,float rotz)
    27.      {
    28.          this.Id = id;
    29.          this.Modelname = modelname;
    30.          this.Posx = posx;
    31.          this.Posy = posy;
    32.          this.Posz = posz;
    33.          this.Rotw = rotw;
    34.          this.Rotx = rotx;
    35.          this.Roty = roty;
    36.          this.Rotz = rotz;
    37.      }
    38. }
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    You can use Unity built-in JSON serialization, no need to do it manually.
     
  3. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    For that I need to convert all the contents in the list to a string ...Right??
     
  4. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    No, wrong. It will convert objects (including lists) to strings and vice versa for you.
     
  5. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    But it won't work with properties, you'll need to create serialized backing fields for the properties.
     
  6. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    Of course it won't. Property is just a shortcut for a pair of methods, getter and setter. It is not possible to serialize "method value" because there's no such thing as method value. Only fields have values.
     
  7. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    You and I know that, but the OP may very well not, so I thought it best to mention it and save some possible confusion, as his class contains lots of properties.
     
    Last edited: Aug 16, 2019
    lordofduct likes this.
  8. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    ok if I removed that...the properties....but how to add all the contents of List into Json.
    Code (CSharp):
    1. string Jsonstring = JsonUtility.ToJson(SaveValues);
    this is not working while the below code is working
    Code (CSharp):
    1. string Jsonstring = JsonUtility.ToJson(SaveValues[0]);
     
  9. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    JsonUtility doesn't support top level arrays, use this helper class http://www.boxheadproductions.com.au/deserializing-top-level-arrays-in-json-with-unity/

    This is an extended version of that class which I use myself...
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class JsonHelper
    6. {
    7.     //Usage:
    8.     //YouObject[] objects = JsonHelper.getJsonArray<YouObject> (jsonString);
    9.     public static T[] jsonToArray<T>(string json)
    10.     {
    11.         //string newJson = "{ \"array\": " + json + "}";
    12.         Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
    13.         return wrapper.array;
    14.     }
    15.  
    16.     //Usage:
    17.     //List<YouObject> objects = JsonHelper.jsonToList<YouObject> (jsonString);
    18.     public static List<T> jsonToList<T>(string json)
    19.     {
    20.         return new List<T>(jsonToArray<T>(json));
    21.     }
    22.  
    23.     //Usage:
    24.     //string jsonString = JsonHelper.arrayToJson<YouObject>(objects);
    25.     public static string arrayToJson<T>(T[] array)
    26.     {
    27.         Wrapper<T> wrapper = new Wrapper<T>();
    28.         wrapper.array = array;
    29.         return JsonUtility.ToJson(wrapper);
    30.     }
    31.  
    32.     //Usage:
    33.     //YouObject[] objects = JsonHelper.getJsonArray<YouObject> (jsonString);
    34.     public static T jsonToValueType<T>(string json)
    35.     {
    36.         //string newJson = "{ \"array\": " + json + "}";
    37.         ValueTypeWrapper<T> wrapper = JsonUtility.FromJson<ValueTypeWrapper<T>>(json);
    38.         return wrapper.value;
    39.     }
    40.  
    41.     //Usage:
    42.     //string jsonString = JsonHelper.arrayToJson<YouObject>(objects);
    43.     public static string valueTypeToJson<T>(T value)
    44.     {
    45.         ValueTypeWrapper<T> wrapper = new ValueTypeWrapper<T>();
    46.         wrapper.value = value;
    47.         return JsonUtility.ToJson(wrapper);
    48.     }
    49.  
    50.     [System.Serializable]
    51.     private class Wrapper<T>
    52.     {
    53.         public T[] array;
    54.     }
    55.  
    56.     [System.Serializable]
    57.     private class ValueTypeWrapper<T>
    58.     {
    59.         public T value;
    60.     }
    61. }
     
    Last edited: Feb 22, 2019
    zyonneo and palex-nx like this.
  10. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    How about this one...Simple...Your answer....is way too advanced....I am a beginner..;)

    public struct ListContainer
    {
    public List<HandleValues> SaveValues;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="_dataList">Data list value</param>
    public ListContainer(List<HandleValues> _dataList)
    {
    SaveValues = _dataList;
    }
    }
     
  11. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    I've added two methods to your ListContainer, the first returns a json string representation of the HandleValues list and the second returns a new list container populated with the values contained in the supplied json string.

    Code (CSharp):
    1.     public struct ListContainer
    2.     {
    3.         public List<HandleValues> SaveValues;
    4.  
    5.         /// <summary>
    6.         /// Constructor
    7.         /// </summary>
    8.         /// <param name="_dataList">Data list value</param>
    9.         public ListContainer(List<HandleValues> _dataList)
    10.         {
    11.             SaveValues = _dataList;
    12.         }
    13.  
    14.         public string ToJson()
    15.         {
    16.             return JsonHelper.arrayToJson(SaveValues.ToArray());
    17.         }
    18.  
    19.         public static ListContainer FromJson(string json)
    20.         {
    21.             return new ListContainer(JsonHelper.jsonToList<HandleValues>(json));
    22.         }
    23.     }
    I don't really know how to make it any simpler, sorry.
     
    zyonneo likes this.
  12. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    I got it using the above which I mentioned earlier
     
  13. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    Last time I soved with your help...Same problem can you take look at this question abt mine . I am sending list in both cases.In one I am getting using your method but in the other I am not getting jsonstring.

    https://forum.unity.com/threads/how...to-json-code-not-working.728462/#post-4861187
     
  14. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    I tried your method....





    Code (CSharp):
    1.  
    2.  
    3. public class PlayerHandler
    4. {
    5.     public int id;
    6.     public Vector2 allposition;
    7.     public Quaternion allrotation;
    8.     public Vector2 allscale;
    9.    
    10.  
    11.  
    12.     public PlayerHandler(int ids,Vector2 allpos,Quaternion allrot,Vector2 allscal)
    13.     {
    14.         this.id = ids;
    15.         this.allposition = allpos;
    16.         this.allrotation = allrot;
    17.         this.allscale = allscal;
    18.        
    19.     }
    20.  
    21.    
    22. }
    23.  
    24. List<PlayerHandler> getAlldata;
    25.  
    26.  
    27. public struct ListContainer
    28.     {
    29.  
    30.         public static List<PlayerHandler> SaveValues;
    31.  
    32.         public ListContainer(List<PlayerHandler> _saveVal)
    33.         {
    34.             SaveValues = _saveVal;
    35.         }
    36.  
    37.     }
    38.  
    39. //get all data contains customized data
    40. ListContainer container = new ListContainer(getAlldata);
    41.  
    42. //I am getting null string below after using Jsonhelper class
    43. //also the Savevalue contains items(not empty)
    44. string jsonstring = JsonHelper.arrayToJson(ListContainer.SaveValues.ToArray());
    45.         Debug.Log("string is = " + jsonstring);
     
  15. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    Looking at the code you've provided it looks like getAlldata is still null when you serialize it, so I'd expect arrayToJson to return an empty string in that case.

    Edit: In fact it would give a null ref error, not return an empty string.
     
    Last edited: Aug 16, 2019
  16. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    I have Printed the GetAllData below
    Code (CSharp):
    1. Get All data = (-3.9, -2.3) : (0.0, 0.0, 0.0, 1.0) : (1.0, 1.0)
    2. Get All data = (-1.2, -6.8Get All data = (3.4, -5.4) : (0.0, 0.0, 0.0, 1.0) : (1.0, 1.0)
    3. Get All data = (3.6, -2.6) : (0.0, 0.0, 0.0, 1.0) : (1.0, 1.0)
    4. Get All data = (-3.2, 2.5) : (0.0, 0.0, 0.0, 1.0) : (1.0, 1.0)
    5. Get All data = (-0.7, 6.1) : (0.0, 0.0, 0.0, 1.0) : (1.0, 1.0)
    6. Get All dataGet All data = (3.8, 2.3) : (0.0, 0.0, 0.0, 1.0) : (1.0, 1.0)
    7. looks like some data are null
     
  17. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    Your player handler struct wasn't marked as serializable also the SaveValues field of the ListContainer shouldn't be static.

    I've whipped up a working example, which results in a debug.log result of:-

    string is = {"array":[{"id":10,"allposition":{"x":20.0,"y":30.0},"allrotation":{"x":0.5597265362739563,"y":0.1612740159034729,"z":0.27709752321243288,"w":0.7641425132751465},"allscale":{"x":80.0,"y":90.0}}]}
    UnityEngine.Debug:Log(Object)
    TestJson:Start() (at Assets/Garador/Skills System/Skills/TestJson.cs:15)


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class TestJson : MonoBehaviour
    6. {
    7.     List<PlayerHandler> getAlldata = new List<PlayerHandler>();
    8.  
    9.     void Start()
    10.     {
    11.         getAlldata.Add(new PlayerHandler(10, new Vector3(20, 30, 40), Quaternion.Euler(50, 60, 70), new Vector2(80, 90)));
    12.         ListContainer container = new ListContainer(getAlldata);
    13.  
    14.         string jsonstring = JsonHelper.arrayToJson(container.SaveValues.ToArray());
    15.         Debug.Log("string is = " + jsonstring);
    16.     }
    17. }
    18.  
    19. public struct ListContainer
    20. {
    21.     public List<PlayerHandler> SaveValues;
    22.  
    23.     public ListContainer(List<PlayerHandler> _saveVal)
    24.     {
    25.         SaveValues = _saveVal;
    26.     }
    27. }
    28.  
    29.  
    30. [System.Serializable]
    31. public class PlayerHandler
    32. {
    33.     public int id;
    34.     public Vector2 allposition;
    35.     public Quaternion allrotation;
    36.     public Vector2 allscale;
    37.  
    38.     public PlayerHandler(int ids, Vector2 allpos, Quaternion allrot, Vector2 allscal)
    39.     {
    40.         this.id = ids;
    41.         this.allposition = allpos;
    42.         this.allrotation = allrot;
    43.         this.allscale = allscal;
    44.     }
    45. }
     
    Last edited: Aug 16, 2019
    zyonneo likes this.
  18. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    Really appreciate that code...thnks....Why Do I forget that all the time...[System.Serilizable]....:(
     
  19. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    This was what i was referring to can be done using jsonutility also...