I normally work with simple serializable fields like int and floats like player speed. What does it do with a whole entire class?
πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/KijoSenzo
πŸ“…︎ Dec 04 2021
🚨︎ report
Why is this not JSON serializable?

I'm just trying to retrieve some data from my flask database, but it isn't JSON serializable so I can't send it to my frontend. The logs actually retrieve it, its just sending it to the frontend that is the issue.

app.py:

class Joke(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    joke_name = db.Column(db.String(40), nullable=False)
    joke = db.Column(db.String(5000), nullable=False)
    joke_owner = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    joke_category = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=False)
    
    def __repr__(self):
        return f"Joke('{self.id}','{self.joke_name}','{self.joke}','{self.joke_owner}','{self.joke_category}')"


class JokeSchema(ma.Schema):
    class Meta:
        fields = ('id', 'joke_name', 'joke', 'joke_owner', 'joke_category')


joke_schema = JokeSchema()
jokes_schema = JokeSchema(many=True)

@app.route("/display/<int:joke_id>/", methods = ['GET'])
def display_joke(joke_id):
    print("lofi here")
    joke = Joke.query.filter_by(id=joke_id).first()
    print(joke)
    return {'joke':joke}

When I try to run this for joke id 15 I get this error in logs:

2021-11-26T23:42:48.299323+00:00 app[web.1]: Joke('5','scar lengthening','eventually scar tissue lengthens when they get tired of being pulled','1','5')
2021-11-26T23:42:48.299808+00:00 app[web.1]: [2021-11-26 23:42:48,299] ERROR in app: Exception on /display/5/ [GET]
2021-11-26T23:42:48.299809+00:00 app[web.1]: Traceback (most recent call last):
2021-11-26T23:42:48.299809+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 2447, in wsgi_app
2021-11-26T23:42:48.299810+00:00 app[web.1]: response = self.full_dispatch_request()
2021-11-26T23:42:48.299810+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1953, in full_dispatch_request
2021-11-26T23:42:48.299810+00:00 app[web.1]: return self.finalize_request(rv)
2021-11-26T23:42:48.299810+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1968, in finalize_request
2021-11-26T23:42:48.299811+00:00 app[web.1]: response = self.make_response(rv)
2021-11-26T23:42:48.299811+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 2112, in make_response
... keep reading on reddit ➑

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/miamiredo
πŸ“…︎ Nov 27 2021
🚨︎ report
Serializable object not transmitting properly through ObjectOutputStream.

Essentially, I am making a rudimentary messaging app akin to Discord. It sends messages and files between clients and a server. There are several classes involved, but I'll only explain what's relevant.

The Data class implements serializable, and has the following instance variables:

  • String userName
  • Date date
  • int type //for the client and server to know what do do with the message
  • String key //for encryption
  • String inputStringToEncrypt //only matters in construction, not relevant for my issue.

There are also two children of the Data class, but since only one is currently functional, that's the one I'll be using.

MessageData:

  • String message

The sendData() method in the Client class is:

public void sendData(){
    try {
        outToServer.writeObject(dataToSendToServer); 
        //outToServer is ObjectOutput Stream
        //dataToSendToServer is a Data object
    }catch( IOException e){
        System.err.println("IO Error Sending Data");
    }
}

Notably, the Client is already connected to the server via a Socket in the start() method. I also added a little print() statement which confirms that the Data object being sent has all the data it should.

The receiveData() method in the ServerSideClientIO class is:

public void receiveData(){
    try{
        dataToReceiveFromClient = (ClackData) inFromClient.readObject();
        System.out.println(dataToReceiveFromClient);
    }catch( IOException e){
        System.err.println("IO Error Receiving Data");
    }catch( ClassNotFoundException e) {
        System.err.println("Receiving Class Not Found Error");
    }
}

The print statement there outputs the message correctly, but the userName and date are null. If anyone can help, I would really appreciate it.

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Quantum_Mechanist
πŸ“…︎ Dec 09 2021
🚨︎ report
serialize using json_serializable

So let's assume I have this json:

{
  "weight" : {
    "10/12/2020" : "60",
    "10/11/2020" : "60",
    "10/10/2020" :"60",
    "10/9/2020"  : "59"
  },
  "height" : {
        "10/11/2020" : "170",
    "10/10/2020" :"170",
    "10/9/2020"  : "170"
  }
}

both weight and height contain dynamic attribute, I can't know what the key is and how many. Anyway, Im using the json_serializable package in flutter, so I want to make the above as a model and then get the data. So, I'm doing this:

import 'package:json_annotation/json_annotation.dart';

part 'response.g.dart';

@JsonSerializable()
class Response {
  final Weight weight;
  final Height height;
  Response({
    required this.cases,
    required this.deaths,
  });

    factory Response.fromJson(Map<String, dynamic> json) =>
      $ResponseFromJson(json);
  Map<String, dynamic> toJson() => $ResponseToJson(this);
}

@JsonSerializable()
class Weight {
   final Map<String, dynamic> weight;
  Weight({
    required this.weight,
    });
      factory Weight.fromJson(Map<String, dynamic> json) =>
      $WeightFromJson(json);
  Map<String, dynamic> toJson() => $WeightToJson(this);
}

@JsonSerializable()
class Height {
  final Map<String, dynamic> height;
  Height({
    required this.height,
  });
        factory Height.fromJson(Map<String, dynamic> json) =>
      $HeightFromJson(json);
  Map<String, dynamic> toJson() => _$HeightToJson(this);
}

So, the above is my modal, but the problem is that the code generation is returning:

Response $ResponseFromJson(Map<String, dynamic> json) {
  return Response(
    cases: Weight.fromJson(json['weight'] as Map<String, dynamic>),
    deaths: Height.fromJson(json['height'] as Map<String, dynamic>),
  );
}

Map<String, dynamic> $ResponseToJson(
        Response instance) =>
    <String, dynamic>{
      'weight': instance.weight,
      'height': instance.height
    };

Weight $WeightFromJson(Map<String, dynamic> json) {
  return Weight(
    weight: Map<String, dynamic>.from(json['weight'] as Map),
  );
}

Map<String, dynamic> $WeightToJson(Weight instance) => <String,
... keep reading on reddit ➑

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/learningcodes
πŸ“…︎ Nov 02 2021
🚨︎ report
TypeError: Object of type ManyRelatedManager is not JSON serializable in django rest framework

am trying to add some students to a teacher class using their ids as primary key but I am getting above error.

I have models of Teachers and Students like this.

class Student(TimeStampAbstractModel):
    user = models.OneToOneField(User, related_name="student", on_delete=models.CASCADE)
    college_name = models.CharField(max_length=255, default="", blank=True)
    address = models.CharField(max_length=255, default="", blank=True)

    def __str__(self):
        return self.user.name

class Teacher(TimeStampAbstractModel):
    user = models.OneToOneField(User, related_name="teacher", on_delete=models.CASCADE)
    address = models.CharField(max_length=255, default="", blank=True)
    students_in_class = models.ManyToManyField(Student,related_name="teacher")

    def __str__(self):
        return self.user.name
Here a teacher model can have many students in a class with thier ids. I have used an put api call to add the students to the teacher in one click.

My view:

from rest_framework import status
class AddtoClassView(APIView):
    

    def put(self,request,pk,*args,**kwargs):
        id =pk
        teacher = Teacher.objects.get(id=id)
        serializer = TeacherSerializer(teacher,data=request.data)
        if serializer.is_valid():
            serializer.save()
            print("iam if")
            return Response({
                "message":"Student has been added to class.",
                "data": serializer.data
            },status=status.HTTP_200_OK)

        # else:
        print("iam else")
        return Response(serializer.data)
My serializer:

class TeacherSerializer(serializers.ModelSerializer):
    students_in_class = serializers.PrimaryKeyRelatedField(
        read_only= True
    )
    address = serializers.CharField(required=False)
    # user = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Teacher
        fields = ["address","students_in_class"]
        # fields = '__all__'

    def update(self, instance, validated_data):
        instance.address = validated_data.get("address")
        instance.save()
        stu = validated_data.get("students_in_class")
        print(stu)
        if stu is not None:
            print("iam stu")
            instance.students
... keep reading on reddit ➑

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/KOP79
πŸ“…︎ Oct 15 2021
🚨︎ report
Help with Object of type set is not JSON serializable
def add_fields():
    fieldCount = 2
    fieldLabel = Properties[0][2][0].value
    for field in Properties[0]:
        if fieldLabel == Properties[0][fieldCount][0].value:
            label = ("'label': " + str(Properties[0][fieldCount][3].value))
            value = ("'value': " + str(Properties[0][fieldCount][4].value))
            displayOrder = ("'displayOrder': " + str(Properties[0][fieldCount][5].value))
            isDefault = ("'isDefault': " + str(Properties[0][fieldCount][6].value))
            fieldOptions.extend([label, value, displayOrder, isDefault])
            fieldLabel = Properties[0][fieldCount][0].value
            fieldCount += 1
        if fieldLabel != Properties[0][fieldCount][0].value:
            fieldOptionString = ''
            for option in fieldOptions:
                fieldOptionString = fieldOptionString + str(option) + ', '
            if Properties[0][fieldCount-1][2].value == 'SLCT':
                parameter1 = post('PARAM', {
                    'label': Properties[0][fieldCount-1][0].value,
                    'name': Properties[0][fieldCount-1][0].value,
                    'extRefID': EXAMPLE,
                    'dataType': Properties[0][fieldCount-1][1].value,
                    'displayType': Properties[0][fieldCount-1][2].value,
                    'parameterOptions':[
                        {fieldOptionString
                        },
                    ]
                })
                print('got here')
                print(parameter1)

Hello!

I am having a problem with some code that I am writing and I am hoping someone can help me out.

The cause of my problem: variable named fieldOptionString

Error I get: TypeError: Object of type set is not JSON serializable

What I have done: If I manually type in the string that would be in fieldOptionString, the error goes away. Based on the error provided, it seems to think that the variable is a set, but I added the code to deliberately force it to be a string so that I could make sure it's not. I type it exactly as it prints out with a print(fieldOptionString) command.

Code description: This code reads in information from an excel file and then sends it as a POST command to a website. The first if section gathers all of the information related to the same field into a list, fieldLabel. Once I have gathered the fields I need for this p

... keep reading on reddit ➑

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/rotaryguy2
πŸ“…︎ Jul 25 2021
🚨︎ report
About the redux best practice "Do not put non-serializable values in state or actions" blog.bam.tech/developer-n…
πŸ‘︎ 178
πŸ’¬︎
πŸ“…︎ Jun 23 2021
🚨︎ report
C++ standard library containers transparently backed by disk, supporting arbitrary serializable types github.com/campfireai/lav…
πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/binaryfor
πŸ“…︎ Sep 22 2021
🚨︎ report
GitHub - voidptr9/clone-dom: Lazily cache-and-clone DOM elements with similar serializable attributes github.com/voidptr9/clone…
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/voidptr9
πŸ“…︎ Sep 01 2021
🚨︎ report
Typehole – Automatically generate TypeScript types and interfaces for all serializable runtime values github.com/rikukissa/type…
πŸ‘︎ 115
πŸ’¬︎
πŸ‘€︎ u/rikurouvila
πŸ“…︎ May 15 2021
🚨︎ report
Android Studio Error: "Incompatible types parcelable or serializable and parcelable or serializable of argument djIdFragmentArgs"

I was trying to pass an instance of a parcelized data class from one fragment to another with android navigation safe args and then add the instance as a parameter to another instance of a data class but I got this error, "Incompatible types parcelable or serializable and parcelable or serializable of argument djIdFragmentArgs".

Here is my 1st fragment code:

BasicInfoFragment.kt

binding.buttonContinue.setOnClickListener(View.OnClickListener {
            val newLogin = LoginModel(binding.edittextUsername.text.toString(), binding.edittextEmail.text.toString())
            val action = BasicInfoFragmentDirections.nextDestination(newLogin, binding.edittextUsername.text.toString())
            view.findNavController().navigate(action)
        })

Here is my 1st data class:

LoginModel.kt

@Parcelize
data class LoginModel(
    val email: String,
    val password: String,
) : Parcelable

and my 2nd fragment:

DjIdFragment.kt

binding.buttonSend.setOnClickListener(View.OnClickListener {
            val newDj = DjModel(binding.edittextDjId.text.toString(), args.djIdFragmentArgs, args.username)
            viewModel.createAccount(newDj)
        })

and finally my 2nd data class:

DjModel.kt

data class DjModel(
    val djId: String,
    val login: LoginModel,
    val username: String,
)

Any idea how to fix this? Any help would be appreciated!

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/Notatrace280
πŸ“…︎ Oct 14 2021
🚨︎ report
About the redux best practice "Do not put non-serializable values in state or actions" blog.bam.tech/developer-n…
πŸ‘︎ 23
πŸ’¬︎
πŸ“…︎ Jun 23 2021
🚨︎ report
[json_serializable] fromJson links some nested classes, but not others?

Hi all,

I'm using json_serialiable to deserialize a model composed of three nested classes:

  1. First: Map of Second objects https://pastebin.com/2V2NmAxv
  2. Second: Stores a single Third object field. https://pastebin.com/1UbfNV6W
  3. Third: Map of enums https://pastebin.com/tihCS7bw

Running flutter pub run build_runner build generates a .g.dart file that does not link the "fromJson" function of Third with the constructor of the Second. This causes the nested deserialization to break. Serialization seems to work though. I've been looking at this for days but can't spot the bug. I'm forced to use json_serializable 4.0.1 due to issue.

Second _$SecondFromJson(Map<String, dynamic> json) {
  return Second(
    thirdModel: json['thirdModel'],
  );
}

Map<String, dynamic> _$SecondToJson(Second instance) => <String, dynamic>{
      'thirdModel': instance.thirdModel.toJson(),
    };

Any ideas? Thank you!

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/KomodoBandicoot
πŸ“…︎ Aug 25 2021
🚨︎ report
TypeError: Object of type Timestamp is not JSON serializable - I have tried to fix to no avail, any suggestions or help?

I get the above code when I try to run my python script which is producing a dataframe with a column that has a timestamp data. See the output of the column below:

 ('Last_Access_Date': Timestamp('2019-03-03 18:03:22.310000+0000', tz='UTC')

I was able to successfully run the code when I commented out the timestamp data.

Below is a snippet of what my code generally looks like for reference:

users = client.get("User")

    df = pandas.DataFrame(users)
    fn = list(df["firstName"])
    ln = list(df["lastName"])
    nm = list(df["name"])
    la = list(df["lastAccessDate"])
    Ident = list(df["id"])


    d = {
        "firstName": fn,
        "lastName": ln,
        "name": nm,
        "Gt_Database": db,
        "lastAccessDate": la,
        "id": Ident,
    }


    df2 = pandas.DataFrame(d)

    print(df2)

    return df2

def upload_items(session, items):
    url = ZOHO_API_URL + 'Get_Users/upsert'

    json_dict = {
        'data' : items,
        'duplicate_check_fields': [ 'name' ],
        'trigger' : [ 'workflow' ]
    }

    resp = session.post(url, json=json_dict)

    print(resp.text)

def upload_dataframe_to_zoho(session, df, db):
    items = list()

    for indexDevi, row in df.iterrows():
        item = {
                'Name' : row.get('id'),
                'First_Name' : row.get('firstName'),
                'Last_Name' : row.get('lastName'),
                'Email' : row.get('name'),
                'Last_Access_Date' : row.get('lastAccessDate'),
                'Database' : db,
        }

        if row.get('lastAccessDate') is not None:
            item['Last_Access_Date'] = row.get('lastAccessDate')

        print(item)
        items.append(item)

        if len(items) == 100:
            upload_items(session, items)
            items = []

    if len(items) > 0:
        upload_items(session, items)

I have tried making the following changes under the function def upload_dataframe_to_zoho(session, df, db) and get the following errors:

>'Last_Access_Date' : row.get('lastAccessDate').strftime('%Y-%m-%d')

line 131, in upload_dataframe_to_zoho
    'Last_Access_Date' : row.get('lastAccessDate').strftime('%Y-%m-%d'),
  File "pandas\_libs\tslibs\nattype.pyx
... keep reading on reddit ➑

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/seffpierce
πŸ“…︎ Jun 23 2021
🚨︎ report
JSON serializable widgets

Hey girls and guys of the Flutter community!

Please excuse my ignorance if this question appears stupid. It's just something I've been mulling over on and off for a couple of weeks and want to know if I'm missing any downsides.

So I'm working on a project with some guys that have done a lot of CMS projects in the past and they're keen to get all the content off the app and load it in on startup (with defaults for connectivity issues and whatnot).

One member of the team has created a series of content models in an attempt to facilitate this aim but it's - for my tastes - a little fragile. How do we maintain that stable relationship between the content models and the UI in the long term if the content models need to support multiple versions of the app and likely different designs how does that work?

So anyway, the idea that I'm playing around with is making the widgets that hold any sort of content also be JSON serializable objects. That way we can store the properties of these widgets can be stored offline and easily retrieved. And we can store multiple versions both for app versioning and other things (like other languages). And when we retrieve content according to the app version, location in the app, and language we know it should match up perfectly.

Anyone know of any reason why this wouldn't work? Or any other tips for handling content management in a flutter app?

Thanks in advance Laebrye

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/Laebrye
πŸ“…︎ May 30 2021
🚨︎ report
Trying to make my data persistent with Serializable crashes my app

Hi I'm building an app that has it's main activity as a google map which lets the user add custom markers that show crime and in my second activity I want the user to add additional information. The problem I have is when the user gets to the second activity and goes back to the main activity through the action bar all of the markers they placed are removed. Additionally if I turn my phone from portrait to landscape also all of my markers which I added are removed this also occurs if I 'kill' the app and come back. This leads me to my problem of struggling to pass my marker objects when a new activity is created/re-created. I've been trying to implement these markers as an mutable list of marker objects (called GetLocation) and then in onCreate I check if the list isn't empty and if this is the case I loop through the markers re-adding them on the map. But my app crashes whenever I try to add this layer of persistence with serializable and I don't know why. You can see the specific serializable part of my code that crashes my app when I add it here - https://gist.github.com/M-J-Y-21/45f22c283b0031c0f409c7affbadb86c#file-serializablecrashcode-kt. You can also see the full code here in a link to the project repo - https://github.com/M-J-Y-21/crime-maps-app-custom (Note The serializable code that crashes the app is just in MapsActivity.kt). Just a bit of context I serializeUserMarkers after the user confirms a crime currently I've only done this for the first crime on my spinner object i.e. 'murder' this is why you can see in the github repo code with the when statement all but selectedPosition 1 and 0 are commented. If more context is needed I'd be happy to answer any questions to clarify. Would really appreciate any help. You can see the crash log statement in the comments.

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/MJY-21
πŸ“…︎ May 16 2021
🚨︎ report
Typehole – Automatically generate TypeScript types and interfaces for all serializable runtime values (/r/typescript) github.com/rikukissa/type…
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/ContentForager
πŸ“…︎ May 16 2021
🚨︎ report
library for merging serializable data types

I made a simple serde based library that makes it easy to merge some serializable data types. Hope it will be useful to someone. Any advice or code review is appreciated.
https://crates.io/crates/serde_merge

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/Z4RX
πŸ“…︎ Jul 04 2021
🚨︎ report
not JSON serializable

Hello! I am having a json.dumps issue. My return is not serializable, apparently, and I cannot figure out what to do to overcome this issue. Thoughts? Here is the code:

    def get_timezone(self):
        from timezonefinder import TimezoneFinder
        tf = TimezoneFinder()
        timezone_string = tf.timezone_at(lng=self.data['longitude'], lat=self.data['latitude'])
        timezone = get_time_zone(timezone_string)
        _LOGGER.debug("Timezone: " + str(timezone))
        return json.dumps(timezone)

Here's the error:

 File "/usr/local/lib/python3.8/json/encoder.py", line 179, in default     raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type America/New_York is not JSON serializable

Thank you for looking over this!

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/robertomano
πŸ“…︎ May 16 2021
🚨︎ report
Error "acpi-device"="IOACPIPlatformDevice is not serializable"

CPU: Ryzen 5 5600
GPU: AMD RX480 4GB
Motherboard: Gigabyte X570 I Aorus Pro Wifi
Audio codec: Realtec ALC1220-vb

so I was testing out my USB maps on this hackintosh, and I ran the ioreg -l -p IOService -w0 | grep -i XHC1 command in Terminal. Got results that looked like this:

ioreg -l -p IOService -w0 | grep -i XHC1

| | | | +-o XHC1@0,1 <class IOPCIDevice, id 0x10000022e, registered, matched, active, busy 0 (56 ms), retain 12>

| | | | | | "compatible" = <"pci1022,1486","pci1022,149c","pciclass,0c0330","XHC1">

| | | | | | "acpi-path" = "IOACPIPlane:/_SB/PCI0@0/BXBR@10002/BYUP@0/BYD8@80000/XHC1@1"

| | | | | | "IOReportLegend" = ({"IOReportGroupName"="Interrupt Statistics (by index)","IOReportChannels"=((5291294645182070784,4295098369," First Level Interrupt Handler Count"),(5291294645182070785,4295098369," Second Level Interrupt Handler Count"),(5291294645182070786,4295098369," First Level Interrupt Handler Time (MATUs)"),(5291294645182070787,4295098369," Second Level Interrupt Handler CPU Time (MATUs)"),(5291294645182070788,4295098369,"Second Level Interrupt Handler System Time (MATUs)")),"IOReportChannelInfo"={"IOReportChannelUnit"=0},"IOReportSubGroupName"="XHC1 1"})

| | | | | +-o XHC1@20000000 <class AppleUSBXHCIPCI, id 0x1000002c4, registered, matched, active, busy 0 (56 ms), retain 76>

| | | | | | "name" = <"XHC1">

| | | | | | "device-properties" = {"acpi-device"="IOACPIPlatformDevice is not serializable","acpi-path"="IOACPIPlane:/_SB/PCI0@0/BXBR@10002/BYUP@0/BYD8@80000/XHC1@1"}

| | | | | | | "device-properties" = {"acpi-device"="IOACPIPlatformDevice is not serializable","acpi-path"="IOACPIPlane:/_SB/PCI0@0/BXBR@10002/BYUP@0/BYD8@80000/XHC1@1/RHUB@0/PRT2@2"}

| | | | | | "device-properties" = {"acpi-device"="IOACPIPlatformDevice is not serializable","acpi-path"="IOACPIPlane:/_SB/PCI0@0/BXBR@10002/BYUP@0/BYD8@80000/XHC1@1/RHUB@0/PRT3@3"}

| | | | | | "device-properties" = {"acpi-device"="IOACPIPlatformDevice is not serializable","acpi-path"="IOACPIPlane:/_SB/PCI0@0/BXBR@10002/BYUP@0/BYD8@80000/XHC1@1/RHUB@0/PRT4@4"}

| | | | | | "device-properties" = {"acpi-device"="IOACPIPlatformDevice is not serializable","acpi-path"="IOACPIPlane:/_SB/PCI0@0/BXBR@10002/BYUP@0/BYD8@80000/XHC1@1/RHUB@0/PRT5@5"}

|

... keep reading on reddit ➑

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/WhiskeyGolf00
πŸ“…︎ Aug 20 2021
🚨︎ report
Object of type 'Reddit' is not JSON serializable

New to PRAW, trying to use it following the documentation.

i tried read-only request, something like this:

>import praw
>
>reddit = praw.Reddit(client_id="SI8pN3DSbt0zor", client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", user_agent="testscript by u/test_user")

and authenticated request, something like this:

>reddit = praw.Reddit(client_id="SI8pN3DSbt0zor", client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", password="1guiwevlfo00esyy", user_agent="testscript by u/test_user", username="test_user")

both return the same error,

>TypeError: Object of type 'Reddit' is not JSON serializable

(credentials are swapped out, i used my own id/secret etc in actual script)

Has anyone seen this before? I'm running this in docker, with python flask, if that makes a difference.

EDIT: resolved - looks like praw wasn't imported properly in docker. after removing old images & rebuilt everything works.

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/green_amethyst
πŸ“…︎ Nov 16 2020
🚨︎ report
Why are all of Unity's inbuilt data structures marked as non-serializable?

I'm fairly new to Unity. While writing a game I came to a point where I wanted to save levels in a file from where they could be loaded at runtime. My level consists of different obstacles placed at various locations having different rotations, sizes, colors, etc.

I tried to use binary formatter first (see documentation here) as this allows you to save and read class objects with a single line of code, but its not possible as none of Unity's classes such as Vector3, Color, Quaternion, etc. are marked as serializable. I was forced to write lots of extra code to individually serialize each primitive element of these classes (Vector3.x, Vector3.y, Vector3.z, etc.) and then reconstruct them when loading the level.

I was able to eventually accomplish what I wanted, but it just seemed the wrong way to do it, ended up with clumsy and unnecessary code. I want to use binary files, so XML serialization or text files is not an option. Can someone with more experience share a proper way to write objects containing Unity's data structures to a binary file? There must be a way - tons of games on Steam made in Unity do it!

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/AVK95
πŸ“…︎ Jun 26 2021
🚨︎ report
I created a prototype of validator package inspired by javax and json_serializable. Looking for opinions

I'm looking for opinions and constructive critique of a package I started yesterday.

It's purpose is to annotate fields with validators to create a compile-time validation code. Currently it supports @NotNull @NotBlank @Email for Strings, @NotBefore for DateTime. I created them just to prototype how easy it will be to add new validators, test them and their complexity, so adding new validation should be fairly straightforward.

Example usage for a String field that needs to be not null and not blank (no whitespaces) and .length &gt; 0

import 'package:valid.dart/validators.dart';

part 'complete_model.g.dart';

@Validate()
class Model {
  @NotEmpty(message: "answer must not be null")
  @NotBlank()
  String answer = '3';

  Iterable&lt;ValidationError&gt; validate() =&gt; _$CompleteModelValidator(this);

}

Then calling model.validate() wil return an Iterable of errors, which tell you what field wasn't valid, why it wasn't valid (built-in message), optionally your error message and your reason for validation:

final String fieldName;
final String validationtype;
final String? message;
final String? reason;

The purpose of it is to be general use, technology agnostic (without direct integration with any frontend or backend), include minimal runtime dependencies to avoid any dependency hell.

It's not published on pub.dev yet, as I'm looking for opinions, direction and what you would like to see from such package.

I am simply looking for feedback on direction, use, any suggestion which way to go. Would you use it? Would you contribute to it? What other validators should it include? Should this be method called on an instance? Static method? Throwing errors or returning list?

Link on gitlab, example use

πŸ‘︎ 14
πŸ’¬︎
πŸ‘€︎ u/agilob
πŸ“…︎ Apr 11 2021
🚨︎ report
The `build_it:json` generator now maximally compatible with `json_serializable` package. Design and generate complex JSON classes and enums in minutes for use with `json_serializable`.

https://github.com/mezoni/build_it

Example configuration:

---
format:
  name: build_it
  generator:
    name: build_it:json
---

checkNullSafety: true
jsonSerializable:
  anyMap: true

classes:
- name: Category
  fields:
  - { name: id, type: int? }
  - { name: name, type: String? }
  - { name: products, type: List&lt;Product&gt;, jsonKey: { defaultValue: [] } }

- name: Product
  fields:
  - { name: id, type: int? }
  - { name: name, type: String? }
  - { name: type, type: ProductType, jsonKey: { defaultValue: ProductType.product } }

enums:
- name: ProductType
  values:
  - { name: product, jsonValue: { value: 0 } }
  - { name: service, jsonValue: { value: 1 } }

code: |
  int _foo(String s) {
    return 41;
  }

Generated code:

// GENERATED CODE - DO NOT MODIFY BY HAND

import 'package:json_annotation/json_annotation.dart';

part 'example_classes.g.g.dart';

// **************************************************************************
// build_it: build_it:json
// **************************************************************************

@JsonSerializable(anyMap: true)
class Category {
  Category({this.id, this.name, required this.products});

  /// Creates an instance of 'Category' from a JSON representation
  factory Category.fromJson(Map json) =&gt;
      _$CategoryFromJson(json);

  int? id;

  String? name;

  @JsonKey(defaultValue: [])
  List&lt;Product&gt; products;

  /// Returns a JSON representation of the 'Category' instance.
  Map&lt;String, dynamic&gt; toJson() =&gt; _$CategoryToJson(this);
}

@JsonSerializable(anyMap: true)
class Product {
  Product({this.id, this.name, required this.type});

  /// Creates an instance of 'Product' from a JSON representation
  factory Product.fromJson(Map json) =&gt;
      _$ProductFromJson(json);

  int? id;

  String? name;

  @JsonKey(defaultValue: ProductType.product)
  ProductType type;

  /// Returns a JSON representation of the 'Product' instance.
  Map&lt;String, dynamic&gt; toJson() =&gt; _$ProductToJson(this);
}

enum ProductType {
  @JsonValue(0)
  product,
  @JsonValue(1)
  service
}

int _foo(String s) {
  return 41;
... keep reading on reddit ➑

πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/andrew_mezoni
πŸ“…︎ Mar 19 2021
🚨︎ report
Open Source Observable<T> and ObservableList<T> implementation that integrates perfectly with Unity: serializable, displays nice in inspector, responds to changes from inspector or UNDO system. Available for free.

I have open sourced an implementation of Observable<T> and ObservableList<T> for Unity. Observables allow you to have public fields in your classes that fire events when they are changed. Its a very useful pattern, you no longer need to check if a value has changed each frame in an Update() call.

The goal for this implementation is to keep it simple and integrate it seamlessly with the Unity editor. The observables are serializable and display nicely in the editor. They may be used in runtime scripts or editor scripts. They fire change events due to changes made in the inspector or the UNDO system (this part was quite challenging).

I love to use observables in Unity. They make it much easier to write components that are robust to their public variables being changed at any time. I spent a good while looking for Observable implementations in various forums and blog posts, but none of them integrated perfectly with Unity as listed above. I spent a few days combining these examples and extending them. The scripts are available for free if you may find them useful.

https://github.com/Adam4lexander/UnityObservables

πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/AdamAlexandr
πŸ“…︎ Oct 23 2020
🚨︎ report
Serializable Records inside.java/2020/07/20/se…
πŸ‘︎ 50
πŸ’¬︎
πŸ‘€︎ u/pron98
πŸ“…︎ Jul 20 2020
🚨︎ report
Automatically generate the code needed for json_serializable and jaguar_serializer and automatically run the flutter pub run build_runner build -delete-conflicting-outputs command. Makes developing flutter even easier!

Automatically generate the code needed for json_serializable and jaguar_serializer and automatically run the flutter pub run build_runner build -delete-conflicting-outputs command. Makes developing flutter even easier!

GitHub:https://github.com/LuodiJackShen/AutoJson

Plugin:https://plugins.jetbrains.com/plugin/11600-autojson

πŸ‘︎ 13
πŸ’¬︎
πŸ‘€︎ u/Ok_Pea_2331
πŸ“…︎ Nov 24 2020
🚨︎ report
Generic Serializable Dictionary for Unity 2020.1.0 with a native look and feel. github.com/upscalebaby/ge…
πŸ‘︎ 54
πŸ’¬︎
πŸ“…︎ Feb 16 2020
🚨︎ report
How to define a superclass interface with fromJson while still using code generation package 'json_serializable'

The problem is that the plugin only allows this notation for the fromJson method:

factory Person.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$PersonFromJson(json);

And since that is a factory there is no way to have a superclass which defines this factory so that I can use it the following way:

void doSomeStuffWithSerializableClass(SuperSerializable superS) {
  superS.fromJson(jsonMap);
}
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Hard_Veur
πŸ“…︎ Nov 13 2020
🚨︎ report
laher/marshalfs: Simulates an RO filesystem, backed by serializable objects. It's like a more dynamic fstest.MapFS github.com/laher/marshalf…
πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/R2A2
πŸ“…︎ Feb 20 2021
🚨︎ report
New JSON Serialization Library - Dynamic, Single file, Generator, No manual registration, casting, and bloat (`dart_json_mapper` and `json_serializable` alternative)

Package (dev_dependency): https://pub.dev/packages/simple_jsonSupporting Package (dependency): https://pub.dev/packages/simple_json_mapper

GitHub: https://github.com/FlutterDevTools/simple_json

Why?

  • Simple
  • No messy .g.dart
    files for each serializable file (single root-level file which contains all of the generated code)
  • Dynamic serialization and de-serialization without caring about the actual type
  • Model files stay clean and don't care about the serialization logic (SRP)
  • No need to specify custom object and iterable type casting
  • No bloated reflection on the entire type with linting/analyzer issues

All feedback welcome.

TLDR: I didn't like `json_serializable` (too many .g.dart files and no dynamic serialization) and `dart_json_mapper` (manual iterable registration and bloated reflection code gen via `reflectable`).

πŸ‘︎ 33
πŸ’¬︎
πŸ‘€︎ u/0000010100111001
πŸ“…︎ Jun 21 2020
🚨︎ report
Losing data when loading serializable object from file.

So, right now I have a pretty big, but simple player Object. The getters and setters are irrelevant, so I'm going to leave those out of the snippet.

When I create a player all of the data looks perfect and checking its values with toString shows this, BUT when I save this object, then load it and perform toString again I lose a LOT of data and don't know why.

When I create a character, this is shown to me with toString():

https://i.imgur.com/NvUQbkb.png

I save this object using this code after it's created:

public static void createCharacter(String name, String heroClass) {
    try {
		Player player = new Player(name, heroClass);

		FileOutputStream fos = new FileOutputStream("saves/heroes/" + name + ".ser");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(player);
        oos.close();

	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

Now when it comes to loading the player, things become weird. When I specify to load a character from a file it loses a lot of its data, here's the toString():

https://i.imgur.com/gLSORfg.png

I loaded is using this code:

public static Player loadPlayer(String name) {
    try {
		FileInputStream fis = new FileInputStream("saves/heroes/" + name + ".ser");
		ObjectInputStream ois = new ObjectInputStream(fis);
		Player result = (Player) ois.readObject();
        ois.close();
        
        return (result);

	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
    }
    return (null);
}

I've tried scouring the internet for all of the different ways people have loaded objects from files, but nothing fixes this problem, which leads me to believe I have a fundamental misunderstanding of what my object itself is doing, or how to fix it.

The object in question is this:

public class Player implements Serializable {
    
    private static final long serialVersionUID = 1L;

    @NotNull(message = "Name cannot be null.")
    @NotBlank(message = "Name cannot be blank.")
    private String name;
    
    @NotNull(message = "Class can not be null.")
    @NotBlank(message = "Class cannot be blank.")
    private String heroClass;
    private int health;
    
    @Min(value = 1, message = "Level can't be lower than ze
... keep reading on reddit ➑

πŸ‘︎ 8
πŸ’¬︎
πŸ‘€︎ u/monkey_programmer
πŸ“…︎ Sep 11 2020
🚨︎ report

Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.