The Unmarshall function must throw an error if the JSON input structure is incorrect

I encountered an issue with struct A and B while unmarshalling JSON strings. When a JSON string meant for struct A is unmarshalled correctly, it works fine. However, if the same JSON string is mistakenly unmarshalled into struct B, it still succeeds (which is incorrect).

Is there a way to detect when the wrong JSON input has been erroneously converted to the wrong struct type?

You can review the code provided at: play

package main

import (
    "encoding/json"
    "fmt"
)

type A struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

type B struct {
    Alamat string `json:"alamat"`
    Umur   int    `json:"umur"`
}

func main() {
    var structA A
    var structAA A

    valA := "{\"name\":\"budi\",\"age\":10}"
    valB := "{\"alamat\":\"jakarta\",\"umur\":120}"

    //correct case
    err := json.Unmarshal([]byte(valA), &structA)
    if err != nil {
        fmt.Println("fail unmarshal")
    }

    fmt.Println(structA.Name)
    fmt.Println(structA.Age)

    //unmarshalled successfully but with wrong json
    err = json.Unmarshal([]byte(valB), &structAA)
    if err != nil {
        fmt.Println("fail unmarshal")
    }

    fmt.Println(structAA.Name)
    fmt.Println(structAA.Age)

}

Answer №1

According to the documentation, the function

json.Unmarshal(data []byte, v interface{})
does not behave as expected by default:

By default, object keys that do not correspond to a struct field are ignored (you can use Decoder.DisallowUnknownFields for a different behavior).

This means that JSON properties alamat and umur in your valB will be ignored because they do not match any fields in the struct A, while name and age will be set to their default types.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am looking to eliminate the double quotation marks from a JSON file so that I can properly utilize

How can I successfully save a JSON return into an NSDictionary when there are spaces and double quotes present in the data? Is it possible to parse SBJSON to remove the double quotes before saving to rowsArray? rowsArray: { Rows = ( { ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

Steps to dynamically populate a datatable with JSON data by triggering a click event in jQuery

I am facing an issue with feeding JSON data into datatables when the search button is clicked. The JSON data structure is as follows: [ { "port_code":"BOM", "cont_details_id":"9", "price":"44.000", "cont_price":"500", "c ...

Converting Markdown to HTML using AngularJS

I'm utilizing the Contentful API to retrieve content. It comes in the form of a JSON object to my Node server, which then forwards it to my Angular frontend. This JSON object contains raw markdown text that has not been processed yet. For instance, t ...

Sending JSON data using RestKit POST method

I'm currently working on developing an iOS App for my school. In order to run some statistics later, I have implemented a database and created a Restful Web Service to handle all the necessary functions. To access the Web Service, I am utilizing RestK ...

"Encountering a NullPointerException on Android while trying to parse JSON data fetched from

Encountered an issue while attempting to link phpMyAdmin with MySQL database in Android programming. Here is the segment where I endeavored to receive the output from my php method: public boolean obtainLogin(UserModel userModel) { String username = u ...

Issues with parsing application/json data in NodeJS using Express

As a newcomer to setting up a NodeJS express JSON REST API, I am encountering challenges in retrieving the JSON data from both GET and POST requests. Here is the code snippet that I am currently working with: var bodyParser = require("body-parser"); con ...

Guide to Deserializing a JSON Object in Windows Phone 8.1

Can anyone help me with an issue I'm facing? When I deserialize a JSON object and bind it to my properties, the properties show null values. Here is my code: string s = "{\"response\":{\"status\":\"fail\",\"content& ...

What is the process of transforming the character u0421 into the letter "C"?

After making a post query to the server, I received JSON data that had an incorrect symbol: instead of "Correct," it showed up as "\u0421orrect". How can I properly encode this text? The function parse_json appeared to handle it like "РЎorrect"; T ...

Encountered an unexpected character in C# Json.net during value parsing: [

public class JSON_Explore_Root { public string browse_content { get; set; } public List<JSON_Browse_Content> Content { get; set; } } public class JSON_Browse_Content { public string link { get; set; } public string image { get; set; ...

Tips for managing this JavaScript JSON array

Here is an example of a JSON array: var data = { name: 'Mike', level: 1, children: [ { name: 'Susan', level: 2, }, { name: 'Jake', level: 2 }, { name: 'Roy', level: 2 }, ...

Can structured logging in NLog be utilized without the need for templated messages?

Up until now, our team has been utilizing NLog version 4.4.12 without structured logging. However, for achieving structured logging, we have been relying on https://www.nuget.org/packages/NLog.StructuredLogging.Json/. An advantage of using this extension ...

Is there a way to retrieve attribute values from a JSON object using JMESPath?

I am searching for the value of the _ISSUE_CURRENCY variable. The JSON data I have is as follows: { '#value': 'VR-GROUP PLC', '_ISSUE_CURRENCY': 'EUR', '_PRICING_MULTIPLIER': 1, '_TYPE ...

Find the total count of a specific string within a JSON dataset by utilizing the jq tool

I am looking to find the count of occurrences of "1.2.3.46:8983_emo" in a specific JSON string using jq. This particular value can be found under myApp and myApp_shadow, so the expected count should be 2 My current jq filter is: .cluster.collections.myA ...

The third page of Reddit's JSON data on display

When utilizing the Reddit api, I have found a way to retrieve the json of a page. I have successfully done this for the front page, but now I am wondering how to obtain the json for the third page without navigating through the second page. Is there a met ...

What is the process of transforming a list of arrays, which is in JSON format, into Dart?

Having trouble with the JSON_ANNOTATION feature when dealing with a json that contains nested arrays. Uncertain about how to convert the paths in the array into a single Paths object. Maybe something like this, but it doesn't seem to handle multiple ...

Tips on displaying a particular JSON attribute?

After starting with a JSON string, attempting to convert it into a JSON object and then trying to print a specific field (such as firstName), I am getting undefined. What could be the issue here? Thank you for your help! var string = '{"firstName ...

Tips on extracting the image URL after uploading via Google Picker

I'm currently implementing the Google Drive File Picker on my website for file uploading. Everything seems to be working well, except I am facing an issue with retrieving the image URL for images uploaded through the picker. Below is my current JavaSc ...

What is the convention for using one-letter function names in jQuery and JSON?

Could someone please clarify the functionality of this code snippet? One aspect that I find frustrating about this function is its use of a single-lettered name. How can I determine the purpose of this function and what triggers it to run? function ...

Using double quotes in the argument within the Visual Studio Code launch.json runtimeArgs configuration

I am currently using Visual Studio Code with the 'Debugger for Chrome' extension to debug JavaScript code. However, I am facing a challenge as I need to run an out-of-process pepper plugin while debugging. Typically, outside of Visual Studio Cod ...