Exemplo n.º 1
0
	/**
	 * 普通ajax请求
	 * @param request
	 * @param response
	 */
	public void generalAjax(SimplEntity entity, HttpServletRequest request,HttpServletResponse response){
		AjaxResponseBean ajaxResponseBean=new AjaxResponseBean();
		ajaxResponseBean.setStatus("success");
		ObjectMapper objectMapper = new ObjectMapper();
		/***
		 * 当表单是通过ajax(jquery)提交的
		 * 提交上来的表单编码是 UTF-8 (默认)
		 * 服务器做出响应时需要将 response的编码设置成通request请求一样
		 * 普通表单提交的数据 request.getCharacterEncoding() 为NULL
		 * 
		 */		
		response.setCharacterEncoding(request.getCharacterEncoding());
		System.out.println(request.getCharacterEncoding());
		try {
			ajaxResponseBean.setData(objectMapper.writeValueAsString(entity));
			System.out.println(ajaxResponseBean.getData());
			write(response, ajaxResponseBean);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
Exemplo n.º 2
0
	/**
	 * easyUiForm 表单
	 * @param request
	 * @param response
	 */
	public void easyUiFormGet(SimplEntity entity ,HttpServletRequest request, HttpServletResponse response){
		//System.out.println("cerator");
		AjaxResponseBean ajaxResponseBean=new AjaxResponseBean();
		ajaxResponseBean.setStatus("success");
		ObjectMapper objectMapper = new ObjectMapper();
		/***
		 * 当表单是通过ajax(jquery)提交的
		 * 提交上来的表单编码是 UTF-8 (默认)
		 * 服务器做出响应时需要将 response的编码设置成通request请求一样
		 * 普通表单提交的数据 request.getCharacterEncoding() 为NULL
		 * 而easyuifrom 是对于jquery的一个封装 所有一样要使用  而它提交的表单
		 * request.getCharacterEncoding() 是为 :NULL
		 * 所以设置response.setCharacterEncoding("utf-8");
		 */	
		response.setCharacterEncoding("gbk");
		System.out.println(request.getCharacterEncoding());
		try {
			ajaxResponseBean.setData(objectMapper.writeValueAsString(entity));
			System.out.println(ajaxResponseBean.getData());
			write(response, ajaxResponseBean);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
Exemplo n.º 3
0
  public static void transformarJSON(List<Professor> professores) {

    ObjectMapper mapper = new ObjectMapper();

    try {

      // convert user object to json string, and save to a file
      mapper.writeValue(new File("professores.json"), professores);

      // display to console
      // System.out.println(mapper.writeValueAsString(professor));

    } catch (JsonGenerationException e) {

      e.printStackTrace();

    } catch (JsonMappingException e) {

      e.printStackTrace();

    } catch (IOException e) {

      e.printStackTrace();
    }
  }
Exemplo n.º 4
0
  @RequestMapping("/addUser6")
  public void addUser6(User user, PrintWriter out) {
    log.info("userName is:" + user.getUserName());
    log.info("password is:" + user.getPassword());
    String json = null;
    /** 使用Jackson */
    ObjectMapper map = new ObjectMapper();
    try {
      json = map.writeValueAsString(user);

    } catch (JsonGenerationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JsonMappingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    log.info("使用Jackson:" + json);

    /** 使用fastjson */
    json = JSON.toJSONString(user);
    log.info("使用fastjson:" + json);
    out.write(json);
  }
Exemplo n.º 5
0
 private List<Neo4jRelationship> jsonRelationship(String json) {
   json =
       json.replace("_end", "end")
           .replace("_start", "start")
           .replace("_rel_id", "relId")
           .replace("_type", "type")
           .replace(" ", "");
   ObjectMapper om = new ObjectMapper();
   List<LinkedHashMap<String, Object>> list = new ArrayList<LinkedHashMap<String, Object>>();
   List<Neo4jRelationship> relList = new ArrayList<Neo4jRelationship>();
   try {
     list = om.readValue(json, List.class);
     for (Map m : list) {
       Neo4jRelationship rel = new Neo4jRelationship();
       initRel(m, rel);
       relList.add(rel);
     }
   } catch (JsonParseException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   // return Json.fromJsonAsList(Neo4jRelationship.class, json);
   return relList;
 }
Exemplo n.º 6
0
  public List<Message<?>> createBroadCastMessages(Message<?> message) {

    final List<Message<?>> messages = new ArrayList<Message<?>>();

    List<PlayerAnswer> playerAnswers = (List<PlayerAnswer>) message.getPayload();
    for (PlayerAnswer answer : playerAnswers) {
      logger.info(
          answer.getQuestionNumber() + ":" + answer.getPlayerId() + ":" + answer.getChoice());
    }

    for (String connectionId : clients.keySet()) {
      for (PlayerAnswer answer : playerAnswers) {
        String data = "";
        try {
          data = objectMapper.writeValueAsString(answer);
        } catch (JsonGenerationException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (JsonMappingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        messages.add(
            MessageBuilder.withPayload(data)
                .setHeader(IpHeaders.CONNECTION_ID, connectionId)
                .build());
      }
    }

    return messages;
  }
 public static String makeFinalParamStringWithSign(
     String apiId,
     String messageId,
     String timestamp,
     Map<String, Object> params,
     String secret,
     String contentKey) {
   String result = null;
   if (StringUtils.isNotBlank(apiId)
       && StringUtils.isNotBlank(messageId)
       && StringUtils.isNotBlank(timestamp)
       && StringUtils.isNotBlank(secret)) {
     Map<String, Object> finalMap = new HashMap<String, Object>();
     finalMap.put("ApiId", apiId);
     finalMap.put("MessageID", messageId);
     finalMap.put("TimeStamp", timestamp);
     finalMap.put("Validate", DigestUtils.md5Hex(apiId + secret + timestamp).toUpperCase());
     finalMap.putAll(params);
     ObjectMapper mapper = new ObjectMapper();
     try {
       result = "_data=" + YjBase64Util.encode(mapper.writeValueAsString(finalMap), contentKey);
     } catch (JsonGenerationException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (JsonMappingException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
   return result;
 }
Exemplo n.º 8
0
 /**
  * For JsonMetadata stats are considered optional This method suppresses (and logs) errors if they
  * are encountered.
  *
  * @see org.apache.pig.LoadMetadata#getStatistics(String, Job)
  */
 @Override
 public ResourceStatistics getStatistics(String location, Job job) throws IOException {
   Configuration conf = job.getConfiguration();
   Set<ElementDescriptor> statFileSet = null;
   try {
     statFileSet = findMetaFile(location, statFileName, conf);
   } catch (IOException e) {
     log.warn("could not fine stat file for " + location);
     return null;
   }
   ElementDescriptor statFile = null;
   if (!statFileSet.isEmpty()) {
     statFile = statFileSet.iterator().next();
   } else {
     log.warn("Could not find stat file for " + location);
     return null;
   }
   log.debug("Found stat file " + statFile.toString());
   ResourceStatistics resourceStats = null;
   try {
     resourceStats = new ObjectMapper().readValue(statFile.open(), ResourceStatistics.class);
   } catch (JsonParseException e) {
     log.warn("Unable to load Resource Statistics for " + location);
     e.printStackTrace();
   } catch (JsonMappingException e) {
     log.warn("Unable to load Resource Statistics for " + location);
     e.printStackTrace();
   } catch (IOException e) {
     log.warn("Unable to load Resource Statistics for " + location);
     e.printStackTrace();
   }
   return resourceStats;
 }
Exemplo n.º 9
0
  @RequestMapping(value = "/app/", method = RequestMethod.POST)
  public ResponseEntity<App> createApp(@RequestBody App app, UriComponentsBuilder ucBuilder) {
    System.out.println("Creating App " + app.getTitle());

    if (this.api.getAppService().isExist(app)) {
      System.out.println("A app with name " + app.getTitle() + " already exist");
      return new ResponseEntity<App>(HttpStatus.CONFLICT);
    }

    app = this.api.getAppService().createApp(app);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/app/{appid}").buildAndExpand(app.getAppid()).toUri());

    ObjectMapper mapper = new ObjectMapper();
    try {
      String jsonString = mapper.writeValueAsString(app);
      System.out.print(jsonString);
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return new ResponseEntity<App>(app, headers, HttpStatus.CREATED);
  }
Exemplo n.º 10
0
  private void initExpressways() {
    // load all the jsons and create arrays of 'ramp' objects for each expressway
    final URL resource = getClass().getClassLoader().getResource("/expressways");
    final File directory = new File(resource.getPath());
    final File[] files = directory.listFiles();

    for (final File file : files) {
      // System.out.println(file.getPath());

      try {
        final ObjectMapper om = new ObjectMapper();
        final Ramp[] ramps = om.readValue(new File(file.getPath()), Ramp[].class);

        final Expressway expressway = new Expressway(file.getName().replace(".json", ""), ramps);

        expresswayList.add(expressway);

      } catch (final JsonParseException e) {
        e.printStackTrace();
      } catch (final JsonMappingException e) {
        e.printStackTrace();
      } catch (final IOException e) {
        e.printStackTrace();
      }
    }
  }
  @Override
  @RPCReponse("e_fastplay")
  public ResultVo Quick_Game(LogicRequest args) {
    ResultVo vo = null;

    LobbyUserHelper.checkStopGame();
    ServerstopResultVo srv = (new ServerStopTask()).isServerStop();
    if (srv == null) {
      QuickVo op = null;
      try {
        op = ObjectBeanUtil.JACKSON.readValue(args.getData(), QuickVo.class);
      } catch (JsonParseException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
      } catch (JsonMappingException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
      } catch (IOException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
      }
      QuickJoinRooms jr = new QuickJoinRooms();
      return jr.task(op);
    } else {
      return srv;
    }
  }
  @Override
  @RPCReponse("e_getshakeconfig")
  public ResultVo getShakeConfig(LogicRequest args) {
    ResultVo vo = null;

    Map<String, Class> classes = new HashMap<String, Class>();
    classes.put("list", ShakeTypeVo.class);
    // {"maxb":200,"minb":100,"list":
    // [{"type":1,"chip":200},{"type":2,"chip":2000},{"type":3,"chip":20000},{"type":4,"chip":200000},{"type":5,"chip":2000000}]}
    String bsconfig =
        "{\"maxb\":200,\"minb\":100,\"list\": [{\"type\":1,\"chip\":200},{\"type\":2,\"chip\":2000},{\"type\":3,\"chip\":20000},{\"type\":4,\"chip\":200000},{\"type\":5,\"chip\":2000000}]}"; // LogicPropertyUtil.getString("option.texas.shake");

    try {

      ShakeConfigVo svo = ObjectBeanUtil.JACKSON.readValue(bsconfig, ShakeConfigVo.class);
      svo.setCmd(Definition.SHAKECONFIG);
      svo.setCode(Definition.SUCCESS_CODE);
      return svo;
    } catch (JsonParseException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    } catch (JsonMappingException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    } catch (IOException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    }

    return vo;
  }
Exemplo n.º 13
0
  public static void parseJsonUsingJackson() {

    try {
      ObjectMapper objectMapper = new ObjectMapper();
      // convert json string to object
      Root root = objectMapper.readValue(new File("test.json"), Root.class);

      List<People> list = root.getPeople();

      for (int i = 0; i < list.size(); i++) {
        String id = String.valueOf(list.get(i).getId());
        System.out.println("id: " + id + "\t");
        String peopleName = list.get(i).getName();
        System.out.println("Name: " + peopleName + "\t");
        String peopleSurname = list.get(i).getSurname();
        System.out.println("Surname: " + peopleSurname + "\t");
        String peopleAge = String.valueOf(list.get(i).getAge());
        System.out.println("Age: " + peopleAge + "\t");
        String peopleIsDegree = String.valueOf(list.get(i).isDegree());
        System.out.println("Degree: " + peopleIsDegree);
        System.out.println();
      }

    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (JsonParseException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 14
0
  @Get
  @Produces("application/json")
  public String represent() {

    String userID = (String) getRequestAttributes().get("id");

    User u = userService.findByID(Integer.valueOf(userID), User.class);
    System.out.println(u);

    ObjectMapper om = new ObjectMapper();

    String value = "";
    try {
      // -- ����writeWithDefaultPrettyPrinter()����������Ϊ�˸�ӵĸ�ʽ��
      value = om.writerWithDefaultPrettyPrinter().writeValueAsString(u);

    } catch (JsonGenerationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JsonMappingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return value;
  }
Exemplo n.º 15
0
  public List<Offer> getOffers(String latitude, String longitude) {
    // Request JSON data from the API for offers
    MultivaluedMap<String, String> QueryParams = new MultivaluedMapImpl();
    QueryParams.add("lat", latitude);
    QueryParams.add("long", longitude);
    String json =
        service
            .path("offers")
            .queryParams(QueryParams)
            .accept(MediaType.APPLICATION_JSON)
            .get(String.class);

    List<Offer> offers = null;

    try {
      // Transform this to a list of POJOs
      offers = mapper.readValue(json, new TypeReference<List<Offer>>() {});

      for (Offer offer : offers) {
        Log.d(TAG, "Offer: " + offer.getId() + " decription: " + offer.getDescription());
      }
    } catch (JsonParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JsonMappingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return offers;
  }
  @Override
  protected ArrayList<AppointmentRespDetailBean> doInBackground(String... params) {
    // TODO Auto-generated method stub
    ArrayList<AppointmentRespDetailBean> result = null;
    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpGet = new HttpGet(params[0]);

    // Execute the request
    HttpResponse response;

    try {

      response = httpclient.execute(httpGet);

      // Examine the response status
      Log.i("MagicDoor", response.getStatusLine().toString());

      // Get hold of the response entity
      HttpEntity entity = response.getEntity();
      // If the response does not enclose an entity, there is no need
      // to worry about connection release
      if (entity != null) {
        // create ProfessorDataBean object from Json using
        // ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        try {
          result =
              mapper.readValue(
                  entity.getContent(),
                  new TypeReference<ArrayList<AppointmentRespDetailBean>>() {});

        } catch (JsonParseException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (JsonMappingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return result;
  }
Exemplo n.º 17
0
  @Override
  public Cluster retrieve(long clusterId) {
    System.err.println("!!! UPDATE ClusterDAO.retrieve() !!!");
    Cluster cluster = null;
    try {
      saveClusterStm.setLong(1, clusterId);
      ResultSet res = saveClusterStm.executeQuery();
      if (res.next()) {
        Map<String, String> meta =
            objMapper.readValue(res.getString("meta"), new TypeReference<Map<String, String>>() {});
        //		Map<String, String> terms_meta = new
        // ObjectMapper().readValue(res.getString("terms_meta"), new
        // TypeReference<Map<String,String>>() { });
        //		Map<String, String> posts_meta = new
        // ObjectMapper().readValue(res.getString("posts_meta"), new
        // TypeReference<Map<String,String>>() { });
        Query originatingQuery =
            DAOFactory.getFactory().getQueryDAO().retrieve(res.getLong("id_query"));
        if (meta.get("type").equalsIgnoreCase("geo")) {
          cluster = new GeoCluster(originatingQuery, null);
          // TODO: set the proper parent!
          System.err.println("!!! FIX THE BUG IN LocalDBClusterDAO.retrieve() !!!");
        } else if (meta.get("type").equalsIgnoreCase("semantic")) {
          cluster = new TopicCluster(originatingQuery, null, 0, null);
          System.err.println("!!! FIX THE BUG IN LocalDBClusterDAO.retrieve() !!!");
        } else if (meta.get("type").equalsIgnoreCase("time")) {
          cluster = new TimeCluster(originatingQuery);
        }

        statementPosts.setLong(1, clusterId);
        ResultSet resPosts = statementPosts.executeQuery();
        while (resPosts.next()) {
          Post post = DAOFactory.getFactory().getPostDAO().retrieve(resPosts.getLong("id_post"));
          cluster.addPost(post);
        }

        statementTerms.setLong(1, clusterId);
        ResultSet resTerms = statementTerms.executeQuery();
        while (resTerms.next()) {
          Term term = DAOFactory.getFactory().getTermDAO().retrieve(resTerms.getLong("id_term"));
          cluster.addTerm(term);
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (JsonParseException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return cluster;
  }
Exemplo n.º 18
0
 public static String toJsonStr(Object bean) {
   try {
     String s = jsonObj.writeValueAsString(fix(bean));
     return s;
   } catch (JsonGenerationException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return null;
 }
Exemplo n.º 19
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user_center_activity);
    initControl();
    // this.deleteDatabase("imdata.db");
    share = getSharedPreferences(UserLoginActivity.SharedName, Context.MODE_PRIVATE);
    if (savedInstanceState != null) {
      try {
        mUserInfoItem =
            new ObjectMapper().readValue(savedInstanceState.getString("json"), UserInfoItem.class);
      } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (JsonMappingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      loadLayout.setVisibility(View.GONE);
      mTabsAdapter = new TabPageAdapter(this);
      mViewPager.setAdapter(mTabsAdapter);
      mIndicator.setViewPager(mViewPager);
      if (mUserInfoItem == null) {
        UserLogOutFragment fragment = new UserLogOutFragment(UserCenterActivity.this, true);

        mTabsAdapter.addTab(getString(R.string.user_center_get_info_error), fragment);
        return;
      }

      mTabsAdapter.addTab(
          getString(R.string.user_center_my_Collect),
          new UserCollectFragment(UserCenterActivity.this));
      mTabsAdapter.addTab(
          getString(R.string.user_center_my_Intro), new UserIntroFragment(mUserInfoItem));
      mTabsAdapter.addTab(
          getString(R.string.user_center_exit),
          new UserLogOutFragment(UserCenterActivity.this, false));

      mTabsAdapter.notifyDataSetChanged();
      mViewPager.setCurrentItem(0);
    } else if (!NetWorkHelper.checkNetState(this)) {
      loadLayout.setVisibility(View.GONE);
      loadFaillayout.setVisibility(View.VISIBLE);
    } else {
      initViewPager();
    }
  }
Exemplo n.º 20
0
  public MarketBtce(Currency cur1, Currency cur2) throws ExchangeError {
    super(cur1, cur2, "btce");

    // JSON mapper inialisation
    mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(DeserializationConfig.Feature.USE_BIG_DECIMAL_FOR_FLOATS, false);

    // Ajout d'un deserializer d'ordre customis� pour passer de "[ prix, amount ]" dans le json �
    // "new Order(prix,amount,Type.XXX) en java"
    SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
    testModule.addDeserializer(Order.class, new OrderDeserializer());
    mapper.registerModule(testModule);

    // Ajout d'un deserializer des types customis� pour passer de "ask"(resp. "bid") dans le json �
    // "Type.ASK" (resp. "Type.BID") en java
    testModule = new SimpleModule("MyModule2", new Version(1, 0, 0, null));
    testModule.addDeserializer(Type.class, new TypeDeserializer(true));
    mapper.registerModule(testModule);

    // Verification si la pair <cur1, cur2> est accepte par l'exchange
    URL fee_url;
    Fee f;
    try {
      fee_url =
          new URL(
              "https://btc-e.com/api/2/"
                  + cur1.name().toLowerCase()
                  + "_"
                  + cur2.name().toLowerCase()
                  + "/fee");
      String is = Util.getData(fee_url);
      f = mapper.readValue(is, Fee.class);
      Assert.checkPrecond(
          f.error == null,
          "BTC-E n'autorise pas la pair: <" + cur1.name() + "," + cur2.name() + ">");
      // On set les frais de transaction maintenant qu'on est sur que Btc-e autorise la paire
      // <cur1,cur2>
      fee_percent = Op.mult(f.trade, new Decimal("0.01"));
    } catch (JsonParseException e) {
      e.printStackTrace();
      throw new ExchangeError("JsonParseException: Erreur jackson");
    } catch (JsonMappingException e) {
      e.printStackTrace();
      throw new ExchangeError("JsonMappingException: Erreur jackson");
    } catch (IOException e) {
      e.printStackTrace();
      throw new ExchangeError("IOException: Erreur jackson");
    }
  }
Exemplo n.º 21
0
 public static <T> T getObject(Class<T> clazz, String output) {
   T rt = null;
   ObjectMapper mapper = new ObjectMapper();
   try {
     rt = (T) mapper.readValue(output, clazz);
   } catch (JsonGenerationException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return rt;
 }
Exemplo n.º 22
0
  public static void main(String args[]) {

    JacksonTester tester = new JacksonTester();

    try {
      ObjectMapper mapper = new ObjectMapper();

      JsonNode rootNode = mapper.createObjectNode();
      JsonNode marksNode = mapper.createArrayNode();

      ((ArrayNode) marksNode).add(100);
      ((ArrayNode) marksNode).add(90);
      ((ArrayNode) marksNode).add(85);

      ((ObjectNode) rootNode).put("name", "Mahesh Kumar");
      ((ObjectNode) rootNode).put("age", 21);
      ((ObjectNode) rootNode).put("verified", false);
      ((ObjectNode) rootNode).put("marks", marksNode);

      mapper.writeValue(new File("student.json"), rootNode);

      rootNode = mapper.readTree(new File("student.json"));

      JsonNode nameNode = rootNode.path("name");
      System.out.println("Name: " + nameNode.getTextValue());

      JsonNode ageNode = rootNode.path("age");
      System.out.println("Age: " + ageNode.getIntValue());

      JsonNode verifiedNode = rootNode.path("verified");
      System.out.println("Verified: " + (verifiedNode.getBooleanValue() ? "Yes" : "No"));

      JsonNode marksNode1 = rootNode.path("marks");
      Iterator<JsonNode> iterator = marksNode1.getElements();
      System.out.print("Marks: [ ");

      while (iterator.hasNext()) {
        JsonNode marks = iterator.next();
        System.out.print(marks.getIntValue() + " ");
      }

      System.out.println("]");
    } catch (JsonParseException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /** @param args */
  public static void main(String[] args) {

    EBusJsonConfTool m = new EBusJsonConfTool();
    try {
      m.run();

    } catch (JsonParseException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 24
0
 @Override
 public void onMessage(final Message message, final byte[] pattern) {
   try {
     @SuppressWarnings("unchecked")
     OutBoundCommentProxy proxy =
         objectMapper.readValue(message.toString(), OutBoundCommentProxy.class);
     commentService.broadcastCommment(proxy);
   } catch (JsonParseException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 25
0
 public static String toJSON(Object obj) {
   //    String json = JSON.encode(obj);
   ObjectMapper objectMapper = new ObjectMapper();
   String json = "";
   try {
     json = objectMapper.writeValueAsString(obj);
   } catch (JsonGenerationException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return json;
 }
Exemplo n.º 26
0
  public static <T> String fromObjectToJson(T object) {
    ObjectMapper mapper = new ObjectMapper();
    String json = null;
    try {
      json = mapper.writeValueAsString(object);
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return json;
  }
Exemplo n.º 27
0
  public static <T> String fromObjectListtoJsonArray(List<T> objects) {
    ObjectMapper mapper = new ObjectMapper();
    String jsonArray = null;
    try {
      jsonArray = mapper.writeValueAsString(objects);
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return jsonArray;
  }
Exemplo n.º 28
0
 public List<T> fromJsonArrayToObjectList(String jsonInput) {
   ObjectMapper mapper = new ObjectMapper();
   JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, persistentClass);
   List<T> myObjects = null;
   try {
     myObjects = mapper.readValue(jsonInput, type);
   } catch (JsonParseException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return myObjects;
 }
Exemplo n.º 29
0
 @Override
 public void updateDepth() throws ExchangeError {
   try {
     String is = getJsonDepth();
     super.depth = mapper.readValue(is, Depth.class);
   } catch (JsonParseException e) {
     e.printStackTrace();
     throw new ExchangeError("JsonParseException: Erreur jackson");
   } catch (JsonMappingException e) {
     e.printStackTrace();
     throw new ExchangeError("JsonMappingException: Erreur jackson");
   } catch (IOException e) {
     e.printStackTrace();
     throw new ExchangeError("IOException: Erreur jackson");
   }
 }
Exemplo n.º 30
0
 public static void main(String[] args) {
   ProductService service = new ProductService();
   try {
     List<Map<String, Object>> list = service.getProductByOrderType("25bd7cdb-c883-ae4c");
     System.out.println(JSON.toJSONString(list));
   } catch (JsonParseException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (JsonMappingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }