Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 oliver-jones · May 23, 2018 at 12:51 PM · jsonlists

JSON into Unity Class

Hello,

I am retrieving a JSON message dynamically from an external source. Its a message list;

 {  
    "conversation":{  
       "-LD8kInJ39jHQfrbjz34":{  
          "message":"msg1",
          "read":false,
          "sender":"X8oNADtJmOVSouYNU450d",
          "timestamp":"05/22/2018 22:28:52"
       },
       "-LDBzfk8W-DnGn9dMptw":{  
          "message":"msg2",
          "read":false,
          "sender":"X8oNADtJmOVSouYNU450d",
          "timestamp":"05/23/2018 13:34:54"
       },
       "-LDBzgy9gfQTBk1hi0MT":{  
          "message":"msg3",
          "read":false,
          "sender":"X8oNADtJmOVSouYNU450d",
          "timestamp":"05/23/2018 13:34:59"
       }
    }
 }

I need to then convert this into an Object-Class within Unity. Usually, I do this by using Unity's built in JsonUtility.FromJson.

My Class is a List, within another Class that actually holds the structure.

 [System.Serializable]
 public class ConversationClass{
 
     public string message;
     public string sender;
     public string timestamp;
     public bool read;
 }

The problem is the generated index keys; "-LD8kInJ39jHQfrbjz34" for example. As these break the List array as an index, and I get Unexpected node type.

Any suggestions?

Is there a quick, easy way in which I can reference the keys, and then replace with "0", "1", "2", etc ?

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 Harinezumi · May 23, 2018 at 02:50 PM 0
Share

I think the problem is that the JSON utility built into Unity is not general purpose, that's why it cannot handle the keys, nor can you modify the nodes.
As the documentation suggests, try a more sophisticated JSON parser implementation. $$anonymous$$aybe SimpleJSON would be good enough, or you can adapt it to your purposes.

4 Replies

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

Answer by oliver-jones · May 24, 2018 at 08:34 AM

I accomplished this using SimpleJSON in the end; http://wiki.unity3d.com/index.php/SimpleJSON

I basically just serialised it myself;

 var N = JSON.Parse(_json);
 
 for(int i = 0; i < N["conversation"].Count; i++){
 
     MessageClass.Message.ConversationClass _conversation = new MessageClass.Message.ConversationClass();
     _conversation.message = N["conversation"][i]["message"].Value;
     _conversation.sender = N["conversation"][i]["sender"].Value;
     _conversation.timestamp = N["conversation"][i]["timestamp"].Value;
     _conversation.read = N["conversation"][i]["read"].AsBool;
     _Messages.Contents.conversation.Add( _conversation );
 }

Comment
Add comment · 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
0

Answer by hugopok · May 23, 2018 at 04:26 PM

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System;
 
 [Serializable]
 public class Wrapper
 {
     public List<ConversationClass> conversation = new List<ConversationClass> { new ConversationClass(),new ConversationClass(),new ConversationClass() };
 }
 
 [Serializable]
 public class ConversationClass
 {
     public string message;
     public string sender;
     public string timestamp;
     public bool read;
 }
 
 public class Deserialize : MonoBehaviour {
 
     
     public string path;
 
     // Use this for initialization
     void Start ()
     {
         var json = JsonUtility.ToJson(new Wrapper(),true);
         path = Application.dataPath + "/json.json";
         System.IO.File.WriteAllText(path,json);    
         
     }
     
     // Update is called once per frame
     void Update () {
         
     }
 }

If you put your json in json viewer is read like a class, conversation is a class and not a list, so if you want to have a list you should have a wrapper class, and into this, a list of conversation class. Your key now are variable. you should insert the key into a conversation class, in this way you can retrieve your key without problem

Comment
Add comment · Show 2 · 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 oliver-jones · May 23, 2018 at 05:26 PM 0
Share

Hello, thanks for your reply, but I think you misunderstood my question. I understand the List wrappers, but my issue is that I cannot serialise the nodes with the unique-ids.

avatar image hugopok oliver-jones · May 24, 2018 at 07:29 AM 0
Share

Can you please post your code ? if you can

avatar image
0

Answer by tarahugger · May 24, 2018 at 09:34 AM

Why something so mature as serialization has to be such a pain here with Unity is very frustrating. I'd recommend you check out Json.Net - there are multiple free versions on the store.

  • https://assetstore.unity.com/search?q=jsonnet


You will be able to find lots of help for it on StackOverflow/Google. Unfortunately these unity versions are a little bit behind the offical versions and so are lacking a few features, but its still lightyears ahead of anything else, even Microsoft has adopted it as the standard for .Net Core.


Here's my current code, for underscore formatting.

 using Newtonsoft.Json;
 using System.Text.RegularExpressions;
 using Newtonsoft.Json.Serialization;
 
 namespace BackendSystem
 {
     public interface ISerializationProvider
     {
         T Deserialize<T>(string text);
         string Serialize<T>(T obj);        
     }
         
     public class BackendSerializer : ISerializationProvider
     {
         public BackendSerializer()
         {
             JsonConvert.DefaultSettings = () => new JsonSerializerSettings
             {
                 ContractResolver = new UnderscorePropertyNamesContractResolver(),
                 NullValueHandling = NullValueHandling.Ignore
             };    
         }
         
         public T Deserialize<T>(string text)
         {
             return JsonConvert.DeserializeObject<T>(text);
         }
 
         public string Serialize<T>(T model)
         {
             return JsonConvert.SerializeObject(model);
         }
  
         private class UnderscorePropertyNamesContractResolver : DefaultContractResolver  
         {
             protected override string ResolvePropertyName(string propertyName)
              => Regex.Replace(propertyName, @"(\w)([A-Z])", "$1_$2").ToLower();
         }    
     }
 }



 namespace BackendSystem
 {
     public static class Backend
     {
         public static ISerializationProvider Serializer { get; set; } = new BackendSerializer();   
     }           
 }



And use it...

 var errorResponse = Backend.Serializer.Deserialize<ErrorResponse>(www.downloadHandler.text);

another example.

 result.ResponseSize = www.downloadedBytes;
 result.Received = DateTime.Parse(www.GetResponseHeader("Date"));
 result.StatusCode = (HttpStatusCode) www.responseCode;
 result.Value = Backend.Serializer.Deserialize<T>(www.downloadHandler.text);

etc

 var data = Backend.Serializer.Serialize(new RequestModel
 {
      Provider = o.Provider,
      AccessToken  = o.Token,
      Resource  = o.Resource ?? Backend.Options.ResourceName,
 });   


EDIT: Just realized that i didnt answer your question. You can do what you want with Json.Net like this.

 [System.Serializable]
 public class ConversationClass
 { 
     public string message;
     public string sender;
     public string timestamp;
     public bool read;
 }
 
 void Start()
 {            
     var json = @"{  
         ""conversation"":{  
             ""-LD8kInJ39jHQfrbjz34"": {  
                 ""message"":""msg1"",
                 ""read"":false,
                 ""sender"":""X8oNADtJmOVSouYNU450d"",
                 ""timestamp"":""05/22/2018 22:28:52""
             },
             ""-LDBzfk8W-DnGn9dMptw"": {  
                 ""message"":""msg2"",
                 ""read"":false,
                 ""sender"":""X8oNADtJmOVSouYNU450d"",
                 ""timestamp"":""05/23/2018 13:34:54""
             },
             ""-LDBzgy9gfQTBk1hi0MT"": {  
                 ""message"":""msg3"",
                 ""read"":false,
                 ""sender"":""X8oNADtJmOVSouYNU450d"",
                 ""timestamp"":""05/23/2018 13:34:59""
             }
         }
     }";
     
     var jsonObject = JObject.Parse(json);
     var conversationsEntries = jsonObject["conversation"].Children();           
     var conversations = conversationsEntries.Select(t => t.FirstOrDefault()?.ToObject<ConversationClass>());
 }


alt text


untitled-1.png (52.8 kB)
Comment
Add comment · 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
0

Answer by Tobychappell · May 24, 2018 at 09:52 AM

Instead of converting the conversations into a List(ConversationClass) you could try converting it into a Dictionary(string, ConversationClass) . If that works it seems the easiest/simplest solution and should only require a few lines of code to be changed.

Comment
Add comment · 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

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

87 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

What is the most performant way to handle huge List containing data to frame-sync Objects to 360 video? 0 Answers

Load all Json Files from Resources into a converted list? 3 Answers

How to rapidly assign and reassign component data within gameobjects based off API data 0 Answers

Saving a list to json 1 Answer

Adding more than one item to the list and saving it into JSON file problem 1 Answer


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