【问题标题】:how to apply Json serialization or deserialization in request and response to HTTP method of rest api如何在rest api的HTTP方法的请求和响应中应用Json序列化或反序列化
【发布时间】:2016-05-18 08:04:29
【问题描述】:

我对Java中的Rest api非常陌生。我的问题是如何在发布或获取函数之前将json字符串请求直接转换为java类对象,比如

json string : '{"id":3,"name":name}'

rest api post 方法:

@Post
 public Something postData(Something obj) throws Exception {
} 

那么如何在请求此方法之前应用 json 序列化。 现在我在 postData 方法中转换它。

【问题讨论】:

    标签: java json rest serialization


    【解决方案1】:

    您可以使用Jackson API 来玩 JSON。 对于以下 JSON 数据,可以按如下方式进行 Java 对象映射。

        {
      "id": 123,
      "name": "Pankaj",
      "permanent": true,
      "address": {
        "street": "Albany Dr",
        "city": "San Jose",
        "zipcode": 95129
      },
      "phoneNumbers": [
        123456,
        987654
      ],
      "role": "Manager",
      "cities": [
        "Los Angeles",
        "New York"
      ],
      "properties": {
        "age": "29 years",
        "salary": "1000 USD"
      }
    }
    
    import java.io.File;
    import java.io.IOException;
    import java.io.StringWriter;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.databind.node.ObjectNode;
    import com.journaldev.jackson.model.Address;
    import com.journaldev.jackson.model.Employee;
    
    
    public class JacksonObjectMapperExample {
    
        public static void main(String[] args) throws IOException {
    
            //read json file data to String
            byte[] jsonData = Files.readAllBytes(Paths.get("employee.txt"));
    
            //create ObjectMapper instance
            ObjectMapper objectMapper = new ObjectMapper();
    
            //convert json string to object
            Employee emp = objectMapper.readValue(jsonData, Employee.class);
    
            System.out.println("Employee Object\n"+emp);
    
            //convert Object to json string
            Employee emp1 = createEmployee();
            //configure Object mapper for pretty print
            objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    
            //writing to console, can write to any output stream such as file
            StringWriter stringEmp = new StringWriter();
            objectMapper.writeValue(stringEmp, emp1);
            System.out.println("Employee JSON is\n"+stringEmp);
        }
    
        public static Employee createEmployee() {
    
            Employee emp = new Employee();
            emp.setId(100);
            emp.setName("David");
            emp.setPermanent(false);
            emp.setPhoneNumbers(new long[] { 123456, 987654 });
            emp.setRole("Manager");
    
            Address add = new Address();
            add.setCity("Bangalore");
            add.setStreet("BTM 1st Stage");
            add.setZipcode(560100);
            emp.setAddress(add);
    
            List<String> cities = new ArrayList<String>();
            cities.add("Los Angeles");
            cities.add("New York");
            emp.setCities(cities);
    
            Map<String, String> props = new HashMap<String, String>();
            props.put("salary", "1000 Rs");
            props.put("age", "28 years");
            emp.setProperties(props);
    
            return emp;
        }
    
    }
    

    来源:http://www.journaldev.com/2324/jackson-json-processing-api-in-java-example-tutorial

    【讨论】:

      【解决方案2】:

      您可以使用Gson 或使用JSONObject/JSONArray 类(example here)进行手动序列化/反序列化。还有很多其他方法/库可以做到这一点。

      【讨论】:

      • 是的,我可以在 post 或 get 函数中转换它。我已经看到一些代码在请求到 post 方法之前被转换,我不记得了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多