Giter Site home page Giter Site logo

microsoft / kiota-serialization-json-go Goto Github PK

View Code? Open in Web Editor NEW
4.0 17.0 13.0 251 KB

Kiota serialization provider implementation for Go and JSON

Home Page: https://aka.ms/kiota/docs

License: MIT License

Go 99.01% Dockerfile 0.99%
go golang kiota openapi go-sdk json

kiota-serialization-json-go's Introduction

Kiota Json Serialization Library for Go

Go Serialization Text

The Json Serialization Library for Go is the Go JSON serialization library implementation.

A Kiota generated project will need a reference to a json serialization package to handle json payloads from an API endpoint.

Read more about Kiota here.

Using the Kiota Json Serialization Library

    go get github.com/microsoft/kiota-serialization-json-go

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

kiota-serialization-json-go's People

Contributors

andrueastman avatar ashmrtn avatar baywet avatar dadams39 avatar dependabot[bot] avatar eric-millin avatar github-actions[bot] avatar mbarnes avatar microsoft-github-operations[bot] avatar microsoftopensource avatar rkodev avatar xdpcs avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kiota-serialization-json-go's Issues

ParseNode Failure while processing string literal

Present on github.com/microsoft/kiota-serialization-json-go v0.5.1 & v0.5.2
Related to: #26

call: js.NewJsonParseNodeFactory().GetRootParseNode("application/json", bytes)
where

bytes

{"id":"AAMkADhlNjU5MzMzLTUyYzItNDJmYi04ZTgzLTkzYTE1ZDg0OTRjOQBGAAAAAAC9muvJZ4uvRYeQkyPxt40qBwCDUn-uvuceTb3Zb9F345Q1AAAAAAEMAACDUn-uvuceTb3Zb9F345Q1AAAuZPpRAAA=","@odata.context":"https://graph.microsoft.com/v1.0/$metadata#users('67fc108d-cc22-4a54-96af-7b91c5d34cf2')/messages/$entity","@odata.etag":"W/\"CQAAABYAAACDUn/uvuceTb3Zb9F345Q1AAAuT0ok\"","categories":[],"changeKey":"CQAAABYAAACDUn/uvuceTb3Zb9F345Q1AAAuT0ok","createdDateTime":"2022-06-15T05:27:05Z","lastModifiedDateTime":"2022-06-15T05:27:07Z","bccRecipients":[],"body":{"content":"<html lang=\"en\" style=\"min-height:100%; background:#ffffff\"><head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><meta name=\"eventId\" content=\"aad-identity-protection-weekly-digest-report-v2\"><meta name=\"messageId\" content=\"d4db577e-fe10-4bea-8e6d-164bb1ebb039\"><meta name=\"cloud\" content=\"AZ\"><style id=\"mediaqueries\">
<!--
@media only screen and (max-width: 640px) {
.wrap-dangler
	{padding-right:10%!important}
.wrap-dangler.small-text-center .wrap-dangler.text-center

Receiving error: invalid character '\r' in string literal

ByteValue Stored as Int64 Should it be Base64

Related to Issue #12

When writing the tests to verify outcomes of base data structures, the code is noted to have the same output as in the previous issue. This failure is going to be fixed in an upcoming PR.

Upon inspection, it is noted that the previous behavior was to cast the byte into an int and save it as an int. However, when saving a byte array, the values are saved in base 64. If this is the intended behavior for both data structures,
func TestWriteByteValue(t *testing.T) should be correct.

  • Inspection of PR and function TestWriteByteValue

Serialize Writer Feature Extension Question

The SerializeWriter has the ability to write data to an underlying byte array. However, if you want to clear or reset the data that is currently in the underlying array, this doesn't seem to be an option. Would it be possible to either update the following method?

// Close clears the internal buffer.
func (w *JsonSerializationWriter) Close() error {
     return nil
}

or create another method to be able to basically do the following:
writer: make([]string, 0),
or is there another method that is already taking care of this?

SerialWriter Incorrect Format with additional data

When Writer serializes object, a comma is missing following the @odata.etag entry:

"id":"AAMkAGQ1NzViZTdhLTEwMTMtNGJjNi05YWI2LTg4NWRlZDA2Y2UxOABGAAAAAAAPvVwUramXT7jlSGpVU8_7BwB8wYc0thTTTYl3RpEYIUq_AAAAAAETAAB8wYc0thTTTYl3RpEYIUq_AAAYy16iAAA=",
"@odata.etag":"W/\"CQAAABYAAAB8wYc0thTTTYl3RpEYIUq+AAAZEpnr\"""categories":[],"changeKey"

Error on Nested ItemAttachmentable serialization

Error on Nested ItemAttachmentable serialization #61 is still present in version - kiota-serialization-json-go v1.0.1
Issue - Messageable and Eventable can possess one of the 3 different types of attachments. Item Attachmetables are recursive. In the process of trying to send an object with a Nested ItemAttachmentable object, the following error is returned:

panic: interface conversion: interface is nil, not serialization.Parsable [recovered] panic: interface conversion: interface is nil, not serialization.Parsable

Scenario and the output are exactly same as mentioned in above issue.

Panic deserializing response when some datacenters return a string instead of an int for OneDrive item field

I've recently started seeing panics from the kiota-serialization-json-go library when attempting to deserialize a response from the user/<userID>/drive/root/delta (user's OneDrive delta) endpoint. The cause of the failure is an item that has had extra information attached to it by OneDrive. Specifically, it seems that some information about the image was populated including the image dimensions. The image orientation appears to have been partially populated in the sense that now it's not nil/null but instead empty. A minimal sample response for the failing item is

{
    "@odata.type": "#microsoft.graph.driveItem",
    "@odata.etag": "\"{787C2A2D-DF31-4BAF-9ACC-2FB7D14A4029},1\"",
    "createdDateTime": "2023-06-23T17:52:58Z",
    "id": "01BAFL6LRNFJ6HQMO7V5FZVTBPW7IUUQBJ",
    "lastModifiedDateTime": "2023-06-23T17:52:58Z",
    "name": "woohoo_homer.png",
    "photo": {
        "orientation": ""
    },
    "size": 180589
}

This request had an x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"West US 2","Slice":"E","Ring":"1","ScaleUnit":"002","RoleInstance":"MWH0EPF0009A922"}} header.

When receiving a response for this particular image the library panics trying to cast a string into a float (which is later cast to an int). The relevant stack trace for the failure is

panic: interface conversion: interface {} is *string, not *float64 [recovered]
  panic: interface conversion: interface {} is *string, not *float64

goroutine 51 [running]:
testing.tRunner.func1.2({0x1072a47c0, 0x14000bba960})
  /opt/homebrew/Cellar/go/1.20.3/libexec/src/testing/testing.go:1526 +0x1c8
testing.tRunner.func1()
  /opt/homebrew/Cellar/go/1.20.3/libexec/src/testing/testing.go:1529 +0x384
panic({0x1072a47c0, 0x14000bba960})
  /opt/homebrew/Cellar/go/1.20.3/libexec/src/runtime/panic.go:884 +0x204
github.com/microsoft/kiota-serialization-json-go.(*JsonParseNode).GetFloat64Value(...)
  /go/pkg/mod/github.com/microsoft/[email protected]/json_parse_node.go:406
github.com/microsoft/kiota-serialization-json-go.(*JsonParseNode).GetInt32Value(0x140006a7718?)
  /go/pkg/mod/github.com/microsoft/[email protected]/json_parse_node.go:411 +0x9c
github.com/microsoftgraph/msgraph-sdk-go/models.(*Photo).GetFieldDeserializers.func9({0x107d71e80?, 0x140008a6d00?})
  /go/pkg/mod/github.com/microsoftgraph/[email protected]/models/photo.go:170 +0x34
github.com/microsoft/kiota-serialization-json-go.(*JsonParseNode).GetObjectValue(0x140008a6d20, 0x140008b25a8?)
  /go/pkg/mod/github.com/microsoft/[email protected]/json_parse_node.go:225 +0x368
github.com/microsoftgraph/msgraph-sdk-go/models.(*DriveItem).GetFieldDeserializers.func18({0x107d71e80?, 0x140008a6d20?})
  /go/pkg/mod/github.com/microsoftgraph/[email protected]/models/drive_item.go:283 +0x3c
github.com/microsoft/kiota-serialization-json-go.(*JsonParseNode).GetObjectValue(0x140008a6d60, 0x0?)
  /go/pkg/mod/github.com/microsoft/[email protected]/json_parse_node.go:225 +0x368
github.com/microsoft/kiota-serialization-json-go.(*JsonParseNode).GetCollectionOfObjectValues(0x140008a76a0?, 0x107d3c4c8)
  /go/pkg/mod/github.com/microsoft/[email protected]/json_parse_node.go:251 +0x17c
github.com/microsoftgraph/msgraph-sdk-go/drives.(*ItemItemsItemDeltaResponse).GetFieldDeserializers.func1({0x107d71e80?, 0x140008a7660?})
  /go/pkg/mod/github.com/microsoftgraph/[email protected]/drives/item_items_item_delta_response.go:27 +0x3c
github.com/microsoft/kiota-serialization-json-go.(*JsonParseNode).GetObjectValue(0x140008a7680, 0x107d65500?)
  /go/pkg/mod/github.com/microsoft/[email protected]/json_parse_node.go:225 +0x368
github.com/microsoft/kiota-http-go.(*NetHttpRequestAdapter).Send(0x1400004d400, {0x107d65500?, 0x14000374c90?}, 0x14000606cc0, 0x14000374cf0?, 0x140007e9c70?)
  /go/pkg/mod/github.com/microsoft/[email protected]/nethttp_request_adapter.go:359 +0x294
github.com/microsoftgraph/msgraph-sdk-go/drives.(*ItemItemsItemDeltaRequestBuilder).Get(0x14000374b40, {0x107d65500, 0x14000374c90}, 0x1065abdc8?)
  /go/pkg/mod/github.com/microsoftgraph/[email protected]/drives/item_items_item_delta_request_builder.go:62 +0x104

A coworker and I have been going back and forth trying to debug this and so far we've seen it on requests marked with West US 2 but not West US (we mostly end up hitting those two DCs it seems). Attempts to get other images in OneDrive to have the additional metadata that seems to cause this error have been unsuccessful

Is there any way to gracefully handle this sort of situation?

unsupported AdditionalData type: map[string]*jsonserialization.JsonParseNode Write Object

Version 0.4
Used with msgraph-sdk-go current versionv0.25.0
In the following sequence:

err = objectWriter.WriteObjectValue("", message)
			if err != nil {
				fmt.Printf("Error %d %v\n", err)
				fmt.Println(string(message))
			}

This is the message that is printed out. At first inspection, all of the data appears to be valid (e.g. comma separated)

{"id":"AAMkAGZmNjNlYjI3LWJlZWYtNGI4Mi04YjMyLTIxYThkNGQ4NmY1MwBGAAAAAADCNgjhM9QmQYWNcI7hCpPrBwDSEBNbUIB9RL6ePDeF3FIYAAAAAAEMAADSEBNbUIB9RL6ePDeF3FIYAAAfMZjxAAA=","@odata.etag":"W/\"CQAAABYAAADSEBNbUIB9RL6ePDeF3FIYAAAfMbDG\"","categories":[],"changeKey":"CQAAABYAAADSEBNbUIB9RL6ePDeF3FIYAAAfMbDG","createdDateTime":"2022-05-18T20:58:43Z","lastModifiedDateTime":"2022-05-18T20:58:47Z","bccRecipients":[],"body":{"content":"<html><head>^M
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><style type=\"text/css\" style=\"display:none\">^M
<!--^M
p^M
        {margin-top:0;^M
        margin-bottom:0}^M
-->^M
</style></head><body dir=\"ltr\"><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\">Test 4</div></body></html>","contentType":"html"},"bodyPreview":"Test 4","ccRecipients":[],"conversationId":"AAQkAGZmNjNlYjI3LWJlZWYtNGI4Mi04YjMyLTIxYThkNGQ4NmY1MwAQALOAc1dB-HdMpyprK_YCfKw=","conversationIndex":"AQHYavoMs4BzV0H8d0ynKmsr5gJ8rA==","flag":{"flagStatus":"notFlagged"},"from":{"emailAddress":{"address":"[email protected]","name":"George"}},"hasAttachments":false,"importance":"normal","inferenceClassification":"focused","internetMessageId":"<DM6PR17MB4010DEDD6381E73CA36A22C6F6D19@DM6PR17MB4010.namprd17.prod.outlook.com>","isDraft":false,"isRead":false,"isReadReceiptRequested":false,"parentFolderId":"AAMkAGZmNjNlYjI3LWJlZWYtNGI4Mi04YjMyLTIxYThkNGQ4NmY1MwAuAAAAAADCNgjhM9QmQYWNcI7hCpPrAQDSEBNbUIB9RL6ePDeF3FIYAAAAAAEMAAA=","receivedDateTime":"2022-05-18T20:58:43Z","replyTo":[],"sender":{"emailAddress":{"address":"[email protected]","name":"George"}},"sentDateTime":"2022-05-18T20:58:38Z","subject":"Test 4","toRecipients":[{"emailAddress":{"address":"[email protected]","name":"Mark 8 Project Team"}}],"webLink":"https://outlook.office365.com/owa/?ItemID=AAMkAGZmNjNlYjI3LWJlZWYtNGI4Mi04YjMyLTIxYThkNGQ4NmY1MwBGAAAAAADCNgjhM9QmQYWNcI7hCpPrBwDSEBNbUIB9RL6ePDeF3FIYAAAAAAEMAADSEBNbUIB9RL6ePDeF3FIYAAAfMZjxAAA%3D&exvsurl=1&viewmodel=ReadMessageItem"}

Change to only the email address and display name.

Unable to serialize large ISODurationValue

While testing the JsonSerializationWriter with the following test:

func TestDuration( t *testing.T ){
    jw := NewJsonSerializationWriter()
    duration := serial.NewDuration(5, 2, 4, 14, 30, 12, 45)
    err := jw.WriteISODurationValue("Extended", duration)
    if err != nil{
        t.Errorf("Failure: %v\n", err)
    }
}   

Received the following errors:

panic: weeks are not allowed with years or months [recovered]                                                                                                                                  
        panic: weeks are not allowed with years or months   

Nothing in the originating library suggests that durations cannot be larger than weeks. NOTE:: Changing the leading two integers to 0 will allow for the test to pass.

Json parsing doesn't error on bad input

I expect this test to fail, but it passes

func TestShouldFail(t *testing.T) {
	source := "3 [ }"
	sourceArray := []byte(source)

	parseNode, err := NewJsonParseNode(sourceArray)
	if err != nil {
		t.Error(err)
	}

	result, err := parseNode.GetObjectValue(internal.CreateIntersectionTypeMockFromDiscriminator)
	if err != nil {
		t.Error(err)
	}

	assert.NotNil(t, result)
}

It does error in some cases, such as a non-numeric unicode characters.

Error on Nested ItemAttachmentable serialization

Messageable and Eventable can possess one of the 3 different types of attachments. Item Attachmetables are recursive. In the process of trying to send an object with a Nested ItemAttachmentable object, the following error is returned:

panic: interface conversion: interface is nil, not serialization.Parsable [recovered]
	panic: interface conversion: interface is nil, not serialization.Parsable

goroutine 8 [running]:
testing.tRunner.func1.2({0x10765e680, 0x14000cd4900})
	/opt/homebrew/Cellar/go/1.19.2/libexec/src/testing/testing.go:1396 +0x1c8
testing.tRunner.func1()
	/opt/homebrew/Cellar/go/1.19.2/libexec/src/testing/testing.go:1399 +0x378
panic({0x10765e680, 0x14000cd4900})
	/opt/homebrew/Cellar/go/1.19.2/libexec/src/runtime/panic.go:884 +0x204
github.com/microsoftgraph/msgraph-sdk-go/models.(*Message).Serialize(0x140005bac00, {0x1083a22e8, 0x14000cac930})
	/Users/dadams39/go/pkg/mod/github.com/microsoftgraph/[email protected]/models/message.go:579 +0x1100
github.com/microsoft/kiota-serialization-json-go.(*JsonSerializationWriter).WriteObjectValue(0x14000cac930, {0x106793293?, 0x4}, {0x108387e10, 0x140005bac00}, {0x0, 0x0, 0x0?})
	/Users/dadams39/go/pkg/mod/github.com/microsoft/[email protected]/json_serialization_writer.go:257 +0x240
github.com/microsoftgraph/msgraph-sdk-go/models.(*ItemAttachment).Serialize(0x14000394410, {0x1083a22e8, 0x14000cac930})
	/Users/dadams39/go/pkg/mod/github.com/microsoftgraph/[email protected]/models/item_attachment.go:52 +0x80
github.com/microsoft/kiota-serialization-json-go.(*JsonSerializationWriter).WriteObjectValue(0x14000cac930, {0x0?, 0x0}, {0x108386b78, 0x14000394410}, {0x0, 0x0, 0x107f335a0?})
	/Users/dadams39/go/pkg/mod/github.com/microsoft/[email protected]/json_serialization_writer.go:257 +0x240
github.com/microsoft/kiota-abstractions-go.(*RequestInformation).SetContentFromParsable(0x14000194090?, {0x1083955e0, 0x140002367b0}, {0x10839a418, 0x14000063950}, {0x1067a7195, 0x10}, {0x108386b78?, 0x14000394410?})
	/Users/dadams39/go/pkg/mod/github.com/microsoft/[email protected]/request_information.go:215 +0x23c
github.com/microsoftgraph/msgraph-sdk-go/users.(*ItemMailFoldersItemMessagesItemAttachmentsRequestBuilder).ToPostRequestInformation(0x1400024f1a0, {0x1083955e0, 0x140002367b0}, {0x13262a050?, 0x14000394410}, 0x0)
	/Users/dadams39/go/pkg/mod/github.com/microsoftgraph/[email protected]/users/item_mail_folders_item_messages_item_attachments_request_builder.go:146 +0x1e8
github.com/microsoftgraph/msgraph-sdk-go/users.(*ItemMailFoldersItemMessagesItemAttachmentsRequestBuilder).Post(0x1400024f1a0, {0x1083955e0, 0x140002367b0}, {0x13262a050?, 0x14000394410?}, 0x10492a680?)
	/Users/dadams39/go/pkg/mod/github.com/microsoftgraph/[email protected]/users/item_mail_folders_item_messages_item_attachments_request_builder.go:106 +0x30

It was unclear whether or not this error belonged in the abstraction repository or in this directory. While the error is returned from the Graph API, the error can be returned when trying to serialize the object alone.

Unsupported Data Type with Class Pointers

Upon writing M365 data with JsonSerializationWriter.WriteObjectValue()
Receiving error:

"unsupported AdditionalData type: map[string]*jsonserialization.JsonParseNode"}

It should be noted that when the messageId is pulled from Graph Explorer the Writer is able to parse it correctly. However, I have seen this failure on multiple types of mail. Two different additional data headers are included below:

Number 1:

map[string]interface {} ["@odata.type": *"#microsoft.graph.eventMessageResponse", "isDelegated": *false, 
"endDateTime": map[string]*github.com/microsoft/kiota-serialization-json-go.JsonParseNode ["dateTime": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002a5460), "timeZone": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002a54e0), ], 
"type": *"singleInstance", "responseType": *"accepted", "@odata.etag": *"W/\"DAAAABYAAAB8wYc0thTTTYl3RpEYIUq+AAAfar4a\"", "isOutOfDate": *false, "isAllDay": *false,
 "meetingMessageType": *"meetingAccepted",
 "startDateTime": map[string]*github.com/microsoft/kiota-serialization-json-go.JsonParseNode ["dateTime": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002a5330), "timeZone": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002a53c0), ], ]

Number 2:

map[string]interface {} ["type": *"singleInstance", "isDelegated": *false, "location": map[string]*github.com/microsoft/kiota-serialization-json-go.JsonParseNode ["displayName": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002e5720), "locationType": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002e5780), "uniqueIdType": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002e57e0), ], "startDateTime": map[string]*github.com/microsoft/kiota-serialization-json-go.JsonParseNode ["dateTime": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002e5540), "timeZone": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002e55a0), ], "endDateTime": map[string]*github.com/microsoft/kiota-serialization-json-go.JsonParseNode ["dateTime": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002e5630), "timeZone": *(*"github.com/microsoft/kiota-serialization-json-go.JsonParseNode")(0x140002e5690), ], "meetingMessageType": *"meetingRequest", "meetingRequestType": *"newMeetingRequest", "@odata.type": *"#microsoft.graph.eventMessageRequest", "@odata.etag": *"W/\"CwAAABYAAADSEBNbUIB9RL6ePDeF3FIYAAAAAAsl\"", "isOutOfDate": *false, "responseRequested": *true, "isAllDay": *false, ]

Duplicate Key for WriteInt8Value... and potentially others

Verifying fundamentals of the Writer with the test:

func TestWriteInt8Value(t *testing.T) {
        serializer := NewJsonSerializationWriter()
        value := int8(125)
        serializer.WriteInt8Value("key", &value)
        result, err := serializer.GetSerializedContent()
        assert.Nil(t, err)
        t.Logf("%s\n", string(result[:]))
        assert.Equal(t, fmt.Sprintf("\"key\":%d,", value), string(result[:]))
}

Test fails

   json_serialization_writer_test.go:98:                                                                                                                                                      
                Error Trace:    json_serialization_writer_test.go:98                                                                                                                           
                Error:          Not equal:                                                                                                                                                     
                                expected: "\"key\":125,"                                                                                                                                       
                                actual  : "\"key\":\"key\":125," 

This is due to a control loop failure... See snippet below

func (w *JsonSerializationWriter) WriteInt8Value(key string, value *int8) error {
        if key != "" && value != nil {
                w.writePropertyName(key)
        }
        if value != nil {
                cast := int64(*value)
                return w.WriteInt64Value(key, &cast)
        }
        if key != "" && value != nil {
                w.writePropertySeparator()
        }

The key is written in the first clause and then written again in `WriteInt64Value(key, &cast)... Changes need to be made to Int8. Additional tests should be added for other types for verify functionality.

SerializationWriter producing Incomplete Json objects

Related to Issue #17

When comma is added to payload, parse node still fails to create a message object.
View full data on Pastebin expires in 24 hours from post.
The data is attempted imported in this way:

  parseNode, err := absser.DefaultParseNodeFactoryInstance.GetRootParseNode("application/json",bytes)
    if err != nil{
        fmt.Errorf("Unable to create parseNode:%v\n", err)
    }
    aMessage, err := models.CreateMessageFromDiscriminatorValue( parseNode )
    if err != nil{
        fmt.Printf("Unable to create message: %v\n", err)
    }
    fmt.Printf("Message: %T %v\n", parseNode, parseNode)
    fmt.Printf("Message: %T %v\n", aMessage, aMessage)

Results

Message: *jsonserialization.JsonParseNode &{0x140002854f0}
Message: *models.Message &{{{map[] <nil>} [] <nil> <nil> <nil>} [] [] <nil> <nil> [] <nil> [] [] <nil> <nil> <nil> <nil> <nil> [] <nil> <nil> <nil> <nil> <nil> [] <nil> <nil> [] <nil> <nil> [] <nil> [] <nil> <nil>}

When attempted as described in microsoftgraph/msgraph-sdk-go#141 where
deserializedValue, err := parseNode.GetObjectValue(models.CreateMessageFromDiscriminatorValue)
replaces the aMessage, err assignment

Unable to create message: value is not an object
Message: *jsonserialization.JsonParseNode &{0x14000429d40}

Thoughts?

Improper JSON serialization of Time values

I was debugging some mysterious "400 Bad Request" errors from msgraph-sdk-go and found that this chunk of code:

	credential := msgraph_models.NewPasswordCredential()
	credential.SetDisplayName(&displayName)
	credential.SetEndDateTime(&endDateTime)

	requestBody := msgraph_apps_addpw.NewPasswordCredentialRequestBody()
	requestBody.SetPasswordCredential(credential)
	options := &msgraph_apps_addpw.AddPasswordRequestBuilderPostOptions{
		Body: requestBody,
	}
	result, err := graph.ApplicationsById(id).AddPassword().Post(options)

was resulting in this request body:

{"passwordCredential":{"displayName":"test","endDateTime":2023-04-13 14:35:55.527758542 -0400 EDT}}

and this OData error:

{
    "error": {
        "code": "BadRequest",
        "message":"Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format."
        ...
    }
}

The format of endDateTime is wrong.

I believe DateTimeOffset values must be in ISO 8601-1:2019 format, at least according to .NET docs.

{"passwordCredential":{"displayName":"test","endDateTime":2023-04-13T14:35:55-04:00}}

The current code just converts to a string.

Serialization performance

JsonSerializationWriter looks like it could be a good deal more efficient. With a small change I improved performance by about 50% and the tests pass. Those numbers come from benchmarks, so they only mean so much. I can PR the change at some point if you're interested, if not, no worries.

eric-millin@1366790

Here are the differences in the benchmarks

Current   	  111204	     10472 ns/op	   20806 B/op	     211 allocs/op
AfterChange 	  170420	      6276 ns/op	    2095 B/op	     100 allocs/op

serialization writer doesn't escape double quotes in strings

If a string value contains a single quote the serialization writer doesn't escape it and this produces an invalid JSON representation.

A good example of that is the OData etag field (when trying to serialize to storage after retrieving from the service)

"@odata.etag": "W/\"CQAAABYAAAAs+XSiyjZdS4Rhtwk0v1pGAAC5bsJ2\""

ends up producing

"@odata.etag": "W/"CQAAABYAAAAs+XSiyjZdS4Rhtwk0v1pGAAC5bsJ2""

String serialization can produce invalid JSON for some input strings

Hello, I've recently run into some issues serializing and deserializing data using the Graph SDK when the data contains string fields that have special characters besides the already escaped tab/newline characters. For instance, if I create an email with a body with content type text that contains the backspace character (hex character code 0x08), serialize it using the Graph SDK, and then attempt to deserialize it I get an invalid JSON error message because the backspace character is not properly escaped. The set of characters that requires escaping is available in section 7 of RFC 8259

To better highlight these edge cases I've created a new branch in a fork of the repo with a set of (currently failing) tests. A diff showing just the added tests is here

While I was working on a patch for this issue I noticed that the Graph SDK is using custom logic to perform all character escaping in strings. This made me curious, is there a particular reason not to use golang's standard library json.Marshal or an instance of a standard library encoder? It seems like if HTML-safe encoding wasn't needed then an encoder with that feature turned off and manually removing the additional newline character it adds should do the trick. It also seems like it would avoid some of the issues where some, but not all, character escape sequences are handled since the golang standard library should be well tested for edge cases

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.