Reputation: 400
I created an application where I did the backend using spring mvc and the frontend in angular.
The backend works (tested with Postman) but the frontend doesn't work well. In particular the latter does not show me the list of customers in the table.
Looking at the console I get the error:
Unexpected token c in JSON at position 2 at JSON.parse () at XMLHtt…, text: "[{codeperson=BNCLSN43B12F205R, surname=Bianchi,…ZLLSRN85B52L219T, surname=Zollino, name=Sabrina}
message: "Http failure during parsing for http://localhost:8080/customerbuysproduct/customers-list"
Backend response:
[
{codeperson=BNCLSN43B12F205R, surname=Bianchi, name=Alessandro
},
{codeperson=CRLMRC85M17I921J, surname=Carlini, name=Marco
}
]
Here I entered the code for the backend.
BACKEND:
Dao
@Override
public List<Map<String, Object>> readViewListCustomerJson() {
return jdbcTemplate.queryForList("SELECT codeperson,surname,name FROM customer");
}
Controller
@RequestMapping(value = {"/customers-list"}, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getString() {
return customerDao.readViewListCustomerJson().toString();
}
FRONTEND:
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CustomerListComponent } from './customer-list/customer-list.component';
const routes: Routes = [
{ path: 'view-customer', component: CustomerListComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html
<div class="container p-3 my-3 bg-primary text-white">
</div>
<br>
<div class="container-fluid">
<ul class="navbar-nav">
<li class="nav-item ">
<a routerLink="view-customer" routerLinkActive="d-none" class="nav-link" class="btn btn-primary active" role="button" >Customers</a>
</li>
</ul>
<router-outlet></router-outlet>
</div>
customers.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Customer } from './customer';
@Injectable({
providedIn: 'root'
})
export class CustomerService {
private baseUrl = 'http://localhost:8080/customersbuysproduct/';
constructor(private http:HttpClient) { }
getCustomerList(): Observable<any> {
return this.http.get(`${this.baseUrl}`+'customers-list');
}
}
How can I fix this error?
Upvotes: 0
Views: 353
Reputation: 788
Add below dependency in your code.
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
And modify the controller as below.
@RequestMapping(value = {"/customers-list"}, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getString() {
return JSONArray.toJSONString(customerDao.readViewListCustomerJson());
}
Upvotes: 1