即使我以JSON格式发送数据,也无法将数据发布到后端

时间:2019-06-12 19:45:01

标签: java json angular http glassfish

我想将数据从有角度的前端发布到我的glassfish rest服务器后端。我想将具有ID,名称和价格的菜单数据发送到后端。我收到一个错误(请参见标题),但似乎无法解决。我不知道出了什么问题,希望有人能帮助我。当我打印出数据时,它会打印出对象:{   “ menuid”:“ 2”,   “ name”:“德州培根大餐”,   “价格”:“ 5.5” }

前端打字稿文件:

import {Component, OnInit, ViewChild} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {NgForm} from '@angular/forms';
import {empty, Observable} from 'rxjs';
import {any} from 'codelyzer/util/function';
importwser.js:292 {map} from 'rxjs/operators';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  public codeValue: string;

  codeList = [];

  codeListMcd = [
    {menuid: 1, name: 'Hamburger menu', price: 3.50},
    {menuid: 2, name: 'Big mac menu', price: 5.50},
    {menuid: 3, name: 'Quarter Pounder menu', price: 5.50},
    {menuid: 4, name: 'Maestro burger menu', price: 6.50},
    {menuid: 5, name: 'Big Tasty menu', price: 6.50}
  ];

  codeListKfc = [
    {menuid: 1, name: 'Chicken burger menu', price: 3.50},
    {menuid: 2, name: 'Chicken bucket menu', price: 5.50},
    {menuid: 3, name: 'Spicy chicken menu', price: 5.50},
    {menuid: 4, name: 'Tender chicken menu', price: 6.50},
    {menuid: 5, name: 'Chicken nuggets menu', price: 6.50}
  ];

  codeListBk = [
    {menuid: 1, name: 'Whopper burger menu', price: 3.50},
    {menuid: 2, name: 'Texas Bacon king menu', price: 5.50},
    {menuid: 3, name: 'Double Steakhouse menu', price: 5.50},
    {menuid: 4, name: 'Chili Cheese burger menu', price: 6.50},
    {menuid: 5, name: 'Chicken Tendercrisp menu', price: 6.50}
  ];

  codeListDp = [
    {menuid: 1, name: 'Pizza Shoarma menu', price: 3.50},
    {menuid: 2, name: 'Pizza Roasted veggie menu', price: 5.50},
    {menuid: 3, name: 'Pizza Bbq mixed grill menu', price: 5.50},
    {menuid: 4, name: 'Pizza Hawaii menu', price: 6.50},
    {menuid: 5, name: 'Pizza Americana menu', price: 6.50}
  ];

  codeListNyp = [
    {menuid: 1, name: 'Pizza Double Tasty menu', price: 3.50},
    {menuid: 2, name: 'Pizza Mixed Grill menu', price: 5.50},
    {menuid: 3, name: 'Pizza Margherita menu', price: 5.50},
    {menuid: 4, name: 'Pizza BBQ Meatlovers', price: 6.50},
    {menuid: 5, name: 'Pizza Downtown Doner menu', price: 6.50}
  ];


  @ViewChild('f', {static: true}) form: NgForm;
  menu = {
    menuid: ' ',
    name: ' ',
    price: ' '
  };



  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization: 'my-auth-token'
    })
  };


  constructor(private http: HttpClient) {
  }

  ngOnInit() {
    this.http.get('http://localhost:8080/aquadine-jee/resources/restaurant')
      .subscribe(
        val => {
          const restStr = val;
          console.log(restStr);
          console.log(restStr[0].restaurantName);
          // @ts-ignore
          const restNaam = JSON.stringify(restStr[restStr.length - 1].restaurantName);
          console.log(restNaam);
          if (restNaam.toString() === '"Mcdonalds"') {

            this.codeList = this.codeListMcd;

          } else if (restNaam.toString() === '"Kentucky Fried Chicken"') {
            this.codeList = this.codeListKfc;
          } else if (restNaam.toString() === '"Burger King"') {
            this.codeList = this.codeListBk;
          } else if (restNaam.toString() === '"Dominos pizza"') {
            this.codeList = this.codeListDp;
          } else if (restNaam.toString() === '"New York Pizza"') {
            this.codeList = this.codeListNyp;
          }
        }
      );


  }


  public saveMenu(e): void {

    let name = e.target.value;
    let list = this.codeList.filter(x => x.name === name)[0];

    this.menu.menuid = list.menuid.toString();
    this.menu.name = list.name;
    this.menu.price = list.price;

    console.log(list.menuid);
    console.log(list.name);
    console.log(list.price);


    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };


    const data = {
      menuid: list.menuid.toString(),
      name: list.name,
      price: list.price
    };

    console.log(data);



    this.http.post('http://localhost:8080/aquadine-jee/resources/menu',
      data, httpOptions)


      .subscribe( // subscribe to observable http.post
        res => {
          console.log("response" + " " + res); // log results otherwise log error
        },
        err => {
          console.log('Error occured');
        }
      );
  }
}



后端:

package nl.aquadine.model;

import javax.enterprise.inject.Model;
import javax.persistence.*;

/**
 * @author huipvandenende
 */
@Entity
@Table(name = "menu")
@NamedQueries({
        @NamedQuery(name = "Menu.findOne", query = "select m from Menu m where m.id = :id"),
        @NamedQuery(name = "Menu.getAll", query = "select m from Menu m")
    }
)

public class Menu {

    @Id
    @GeneratedValue
    private long id;

    int menuid;

    private String name;
    private int price;

    public Menu() {
    }

    public Menu(String name, int price, int menuid) {
        this.name = name;
        this.price = price;
        this.menuid = menuid;
    }

  public int getMenuid() {
    return menuid;
  }

  public void setMenuid(int menuid) {
    this.menuid = menuid;
  }

  public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

//    public long getId() {
//        return id;
//    }
//
//    public void setId(long id) {
//        this.id = id;
//    }
  public long getId(){
      return id;
  }
public void setId(long id){
      this.id = id;
}
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

后端存储库文件:

package nl.aquadine.rest;

import nl.aquadine.model.Menu;
import nl.aquadine.service.Impl.RepositoryServiceImpl;
import nl.aquadine.service.RepositoryService;

import javax.ejb.Stateless;
import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;

/**
 * @author huipvandenende
 */

@Path("menu")
public class MenuResource {


    private RepositoryService repositoryService;

    public MenuResource() {

        repositoryService = RepositoryServiceImpl.getInstance();
    }


//    @GET
//    @Produces("application/json")
//    public List<Menu> all() {
//        return repositoryService.getAllMenus();
//    }

  @GET
  @Produces("application/json")
  public Response all(){
    List<Menu> all = repositoryService.getAllMenus();
    return  Response
      .status(200)
      .header("Access-Control-Allow-Origin", "*")
      .entity(all)
      .build();
  }

  @POST
  @Consumes("application/json")
  public Response save(Menu menu){
    repositoryService.save(menu);
    return Response
      .status(201)
      .build();
  }

    @PUT
    @Consumes("application/json")
    public void update(Menu menu) {
        repositoryService.update(menu);
    }

    @DELETE
    @Path("/{id}")
    @Consumes("application/json")
    public void delete(@PathParam("id") Long id) {
        Menu menu = repositoryService.find(id);
        repositoryService.delete(menu);
    }
}

玻璃鱼日志中的错误日志:




[2019-06-05T20:35:07.258+0200] [Payara 5.191] [INFO] [] [] [tid: _ThreadID=32 _ThreadName=http-thread-pool::http-listener-1(4)] [timeMillis: 1559759707258] [levelValue: 800] [[
  Hibernate: select restaurant0_.id as id1_2_, restaurant0_.restaurantAdres as restaura2_2_, restaurant0_.restaurantId as restaura3_2_, restaurant0_.restaurantName as restaura4_2_ from restaurant restaurant0_]]

[2019-06-05T20:35:14.822+0200] [Payara 5.191] [SEVERE] [] [fish.payara.microprofile.opentracing.jaxrs.JaxrsContainerRequestTracingFilter] [tid: _ThreadID=30 _ThreadName=http-thread-pool::http-listener-1(2)] [timeMillis: 1559759714822] [levelValue: 1000] [[
  javax.ws.rs.ProcessingException: Error deserializing object from entity stream.
javax.ws.rs.ProcessingException: Error deserializing object from entity stream.
    at org.glassfish.jersey.jsonb.internal.JsonBindingProvider.readFrom(JsonBindingProvider.java:101)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:257)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:73)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1093)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
    at org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:271)
    at org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:98)
    at org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:81)
    at org.glassfish.jersey.server.spi.internal.ParamValueFactoryWithSource.apply(ParamValueFactoryWithSource.java:75)
    at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:93)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:133)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:200)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:103)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:493)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:415)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:104)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:268)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:704)
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:755)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:575)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$0(WorkerThreadIOStrategy.java:90)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
    at java.lang.Thread.run(Thread.java:748)
Caused by: javax.json.bind.JsonbException: Error deserialize JSON value into type: class java.lang.Integer.
    at org.eclipse.yasson.internal.serializer.IntegerTypeDeserializer.lambda$deserialize$1(IntegerTypeDeserializer.java:48)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.eclipse.yasson.internal.serializer.IntegerTypeDeserializer.deserialize(IntegerTypeDeserializer.java:44)
    at org.eclipse.yasson.internal.serializer.IntegerTypeDeserializer.deserialize(IntegerTypeDeserializer.java:29)
    at org.eclipse.yasson.internal.serializer.AbstractValueTypeDeserializer.deserialize(AbstractValueTypeDeserializer.java:64)
    at org.eclipse.yasson.internal.serializer.ObjectDeserializer.deserializeNext(ObjectDeserializer.java:170)
    at org.eclipse.yasson.internal.serializer.AbstractContainerDeserializer.deserializeInternal(AbstractContainerDeserializer.java:85)
    at org.eclipse.yasson.internal.serializer.AbstractContainerDeserializer.deserialize(AbstractContainerDeserializer.java:61)
    at org.eclipse.yasson.internal.Unmarshaller.deserializeItem(Unmarshaller.java:61)
    at org.eclipse.yasson.internal.Unmarshaller.deserialize(Unmarshaller.java:51)
    at org.eclipse.yasson.internal.JsonBinding.deserialize(JsonBinding.java:45)
    at org.eclipse.yasson.internal.JsonBinding.fromJson(JsonBinding.java:85)
    at org.glassfish.jersey.jsonb.internal.JsonBindingProvider.readFrom(JsonBindingProvider.java:99)
    ... 60 more
]]


0 个答案:

没有答案