zoukankan      html  css  js  c++  java
  • 关于JSON字符串

    向客户端返回JSON字符串有两种方法:

    1.纯手工拼接:

    result.append("{");
    result.append(""timu":""+timu+""");
    result.append(",");
    result.append(""id":""+id3+""");
    result.append("}");

    2.引入jar包(jackson-all-1.7.6.jar)然后根据对象的get方法生成

    package com.lhp.unit;

    import java.io.IOException;
    import java.util.Arrays;
    import java.util.List;

    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.annotate.JsonIgnore;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;

    public class Customer
    {

    public Customer(String name, String age)
    {
    super();
    this.name = name;
    this.age = age;
    }

    private String name;
    private String age;

    public String getName()
    {
    return name;
    }
    public void setName(String name)
    {
    this.name = name;
    }
    public String getAge()
    {
    return age;
    }
    public void setAge(String age)
    {
    this.age = age;
    }

    public String getCity()
    {
    return "beijing";
    }

    @JsonIgnore
    public String getBrith()
    {
    return "01-22";
    }

    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException
    {
    //1.导入jar包(jackson-all-1.7.6.jar)
    //2.创建ObjectMapper对象
    ObjectMapper mapper =new ObjectMapper();
    //3.调用mapper的WriteValueAsString()方法把一个对象转化成json字符串
    Customer customer=new Customer("李营", "20");
    String jsonStr=mapper.writeValueAsString(customer);
    System.out.println(jsonStr);
    //4.注意:JakeSon对象使用get方法来定位JSON对象的属性
    //5.通过添加注解(@JsonIgnore)来忽略某一个get定义的属性

    //转集合:
    List<Customer> customers = Arrays.asList(customer,new Customer("yue", "19"));
    jsonStr = mapper.writeValueAsString(customers);
    System.out.println(jsonStr);
    }
    }

  • 相关阅读:
    37.1 net-- udp传输
    37 net 网络编程
    review
    java day02 记录
    36.2 线程生命周期
    36.1 线程锁
    36 Thread 多线程
    35 编码 ASCII Unicode UTF-8 ,字符串的编码、io流的编码
    34.6 Properties(k,v存储) 和io流结合使用
    今日学习总结
  • 原文地址:https://www.cnblogs.com/liying123/p/6535658.html
Copyright © 2011-2022 走看看