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 Neo-Murakami · Nov 28, 2016 at 08:03 AM · serializationapibinaryformatter

Deserializing byte array to POCO from asp.net webapi

Hey Devs,

I have spent the past couple of days trying to figure an issue I am having with deserializing a bytes array into a POCO dataset.

I have an asp.net webapi project that I am trying return an object as a result dataset. The dataset class is in a seperate project that is just a class library that holds POCOs that the webapi will use to return. The returned object is serialized into bytes using the following class, which exists in my class library.

 public class ObjectConverter
     {
         public static T BytesToObject<T>(byte[] bytes)
         {
             MemoryStream ms = new MemoryStream();
             BinaryFormatter bf = new BinaryFormatter();
             ms.Write(bytes, 0, bytes.Length);
             ms.Seek(0, SeekOrigin.Begin);
 
             var obj = bf.Deserialize(ms);
             var retObj = (T)obj;
 
             return retObj;
         }
 
         public static byte[] ObjectToBytes(object obj)
         {
             BinaryFormatter bf = new BinaryFormatter();
             using (MemoryStream ms = new MemoryStream())
             {
                 bf.Serialize(ms, obj);
                 return ms.ToArray();
             }
         }
     }

I include this class library into Unity and perform an Api request but the deserialization fails on the line bf.Serialize(ms, obj); with the exception:

Serialization Exception: Unexpected binary format at 65;

Now when I create a test project in the same WebApi solution and hit the same requests, the deserialization is fine.

On the Unity side, I am using the following script to make the GET request

 public class HttpHandler : MonoBehaviour
 {
     public bool UseLocalAddress;
     private string _baseUrl;
 
     /// <summary>
     /// </summary>
     /// <typeparam name="T">Object type to be serialized to JSON</typeparam>
     /// <typeparam name="K">Object type your expecting back</typeparam>
     /// <param name="controller">The controller to use</param>
     /// <param name="obj">Object to be serialized to JSON</param>
     /// <param name="callback">The callback function when response is finished</param>
     public void GET<T, K>(ControllerTypes controller, T obj, Action<K> callback)
     {
         var jsonObj = JsonUtility.ToJson(obj);
 
         string ApiAddress = string.Format("{0}{1}?obj={2}", _baseUrl, controller, jsonObj);
 
         UnityWebRequest request = UnityWebRequest.Get(ApiAddress);
 
         StartCoroutine(WaitForRequest(request, callback));
     }
 
     private IEnumerator WaitForRequest<T>(UnityWebRequest request, Action<T> callback)
     {
         yield return request.Send();
 
         T response = default(T);
         if (string.IsNullOrEmpty(request.error))
         {
             Debug.Log(string.Format("REQUEST COMPLETED - Response: {0}", request.downloadHandler.text));
             if (typeof(T).IsPrimitive)
             {
                 response = (T)Convert.ChangeType(request.downloadHandler.text, typeof(T));
             }
             else
             {
                 response = ObjectConverter.BytesToObject<T>(request.downloadHandler.data);
             }
 
             callback(response);
         }
         else
         {
             Debug.Log(string.Format("WaitForRequest() ERROR: {0}", request.error));
         }
     }

And the Class I am trying to serialize is the following

 [Serializable]
     public class UserInfo
     {
         public int UserId;
         public string Username;
         public string Password;
         public string Email;
     }

Does anyone have any ideas?

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

0 Replies

· Add your reply
  • Sort: 

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

Binary serialization layout on different platforms 0 Answers

Which types are actually serializable? Is the documentation incorrect or am I? 3 Answers

How to add strings in a list AND be able to save it and load it? Using playerpref OR serialization 2 Answers

What is the best/easiest way to save a game (or scene) at runtime? 1 Answer

IOException: Sharing violation on path 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