You've already forked json-iterator
							
							
				mirror of
				https://github.com/json-iterator/go.git
				synced 2025-10-31 00:07:40 +02:00 
			
		
		
		
	Fix the incompatible encoding
This commit is contained in:
		
							
								
								
									
										36
									
								
								api_tests/marshal_json_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										36
									
								
								api_tests/marshal_json_test.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,36 @@ | ||||
| package test | ||||
|  | ||||
| import ( | ||||
| 	"bytes" | ||||
| 	"encoding/json" | ||||
| 	"github.com/json-iterator/go" | ||||
| 	"testing" | ||||
| 	"github.com/stretchr/testify/require" | ||||
| ) | ||||
|  | ||||
|  | ||||
| type Foo struct { | ||||
| 	Bar interface{} | ||||
| } | ||||
|  | ||||
| func (f Foo) MarshalJSON() ([]byte, error) { | ||||
| 	var buf bytes.Buffer | ||||
| 	err := json.NewEncoder(&buf).Encode(f.Bar) | ||||
| 	return buf.Bytes(), err | ||||
| } | ||||
|  | ||||
|  | ||||
| // Standard Encoder has trailing newline. | ||||
| func TestEncodeMarshalJSON(t *testing.T) { | ||||
|  | ||||
| 	foo := Foo { | ||||
| 		Bar: 123, | ||||
| 	} | ||||
| 	should := require.New(t) | ||||
| 	var buf, stdbuf bytes.Buffer | ||||
| 	enc := jsoniter.ConfigCompatibleWithStandardLibrary.NewEncoder(&buf) | ||||
| 	enc.Encode(foo) | ||||
| 	stdenc := json.NewEncoder(&stdbuf) | ||||
| 	stdenc.Encode(foo) | ||||
| 	should.Equal(stdbuf.Bytes(), buf.Bytes()) | ||||
| } | ||||
| @@ -93,8 +93,7 @@ func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { | ||||
| 		stream.WriteNil() | ||||
| 		return | ||||
| 	} | ||||
| 	marshaler := obj.(json.Marshaler) | ||||
| 	bytes, err := marshaler.MarshalJSON() | ||||
| 	bytes, err := json.Marshal(obj) | ||||
| 	if err != nil { | ||||
| 		stream.Error = err | ||||
| 	} else { | ||||
|   | ||||
		Reference in New Issue
	
	Block a user