Error encountered while parsing JSON data with Gson: MalformedJsonException

Hello, I am working on a project that involves parsing JSON data. However, I keep encountering a Malformed exception while trying to do so. Below is the code I'm currently using:

 Object listOfGroups = sthService.getSthList();
    
    Gson gson = new Gson();
    
    JsonArray jsonArray = gson.fromJson(listOfGroups.toString(), JsonObject.class)
         .getAsJsonArray("memberNameList");
    
    List<String> myId = gson.fromJson(jsonArray, new TypeToken<ArrayList<String>>() {
    }.getType();
    
      for(JsonElement element : JsonArray) {
    
        Json jsonObject = element.getAsJsonObject();
    
        String sthIndicator = jsonObject.get("readInd").getAsString();
    
        if (sthIndicator.equalsIgnoreCase("Y")) {
    
         String itemId = jsonObject.get("itemId").getAsString();
         myId.add(itemId);
      }
    }

Answer №1

If Gson is unable to match the received JSON string with your JsonObject.class, it may throw an exception due to datatype mismatch.

To resolve this issue, you can either verify the datatypes for each attribute or switch to using ObjectMapper instead of Gson. ObjectMapper can handle the Json String regardless of datatype restrictions.

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

Creating a nested JSON file dynamically in Angular: A step-by-step guide

I am looking to dynamically generate a nested JSON file within an Angular project. The data will be extracted from another JSON file, with two nested loops used to read the information. Below is an example of the initial JSON file structure: { "data": [ ...

You are not able to use *ngIf nested within *ngFor in Angular 2

I am currently working in Angular2 and trying to bind data from a service. The issue I am facing is that when loading the data, I need to filter it by an ID. Here is what I am trying to achieve: <md-radio-button *ngFor="#item of items_list" ...

Ensuring a Generic Type in Typescript is a Subset of JSON: Best Practices

I am interested in achieving the following: interface IJSON { [key: string]: string | number | boolean | IJSON | string[] | number[] | boolean[] | IJSON[]; } function iAcceptOnlyJSON<T subsetof IJSON>(json: T): T { return json; ...

Encountered an issue in Angular 6: Unable to access property '0' of undefined

There's an error popping up in the console saying, Cannot read property '0' of undefined, but surprisingly I'm still getting the expected result. Below is my HTML code snippet: <div class="col-md-3"> <div class="slider-prod ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...

Tips and tricks for displaying JSON data in Angular 2.4.10

In my Angular project, I am facing an issue while trying to display specific JSON data instead of the entire JSON object. Scenario 1 : import { Component, OnInit } from '@angular/core'; import { HttpService } from 'app/http.service'; ...

What is the process of extracting information from a JSON file and how do I convert the Date object for data retrieval?

export interface post { id: number; title: string; published: boolean; flagged: string; updatedAt: Date; } ...

The function 'makeDecorator' does not support function calls when being accessed

Resolved by @alexzuza. Check out his solution below - major props! The issue was with the node_modules folder in the ng2-opd-popup directory, it needed to be removed and the src/tsconfig.app.json file had to be adjusted accordingly. Make sure to also refer ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

Utilizing Typescript with Angular 2 to efficiently convert JSON data into objects within HTTP requests

I am dealing with a file called location.json, which contains JSON data structured like this: { "locations": [ { "id": 1, "places": [ { "id": 1, "city": "A ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

Extract the JSON array data from the Service and process it within the Component

When passing a response from the Service to the Component for display on the UI, each value needs to be parsed and stored in a variable. This can be achieved by extracting values such as profileId, profileName, regionName, etc. from the response. [{"profi ...

Unable to retrieve the key value from a child object in Angular 2 when working with JSON Data

Currently, I am using Angular and attempting to extract data from the child object's key value. Here is the JSON data provided: "other_lessons": [ { "id": 290, "name": "Christmas Test #290", "course": { "id": ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

Developing J2EE servlets with Angular for HTTP POST requests

I've exhausted my search on Google and tried numerous PHP workarounds to no avail. My issue lies in attempting to send POST parameters to a j2ee servlet, as the parameters are not being received at the servlet. Strangely though, I can successfully rec ...

Strange behavior of the .hasOwnProperty method

When attempting to instantiate Typescript objects from JSON data received over HTTP, I began considering using the for..in loop along with .hasOwnProperty(): class User { private name: string; private age: number; constructor(data: JSON) { ...

Spring Boot fails to recognize path variable data sent from Angular

When working with Angular 7, I encountered a situation where I needed to pass a value from the service class of Angular. Here is how I achieved it: executeHelloWorldBeanServiceWithPathVariable(name){ console.log("name coming from here"+name); retu ...

Is it possible to interchange the positions of two components in a routing system?

driver-details.component.ts @Component({ selector: 'app-driver-details', templateUrl: './driver-details.component.html', styleUrls: ['./driver-details.component.css'] }) export class DriverDetailsComponent implements OnI ...

Exploring the Nested JSON Data Loop with *ngFor in Angular 5/4

Recently I started working with Angular, and I've created a service to iterate over nested JSON data for my list. export const CATEGORIES: Category[] = [ { id: 1, categoryName:'Accessories', subcatName: [ {subcategory: & ...