1. 程式人生 > >json 資料轉化為實體類 包含list型別

json 資料轉化為實體類 包含list型別

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;


import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;


import com.fasterxml.jackson.databind.ObjectMapper;
 

import net.sf.json.JSONObject;

public class ApolloUtil {
    
     public static String getApollo(String url,String token){
            String result =“”;
            BufferedReader in = null;
            試試{
                URL realUrl = new URL(url);
                //開啟和URL之間的連線
                URLConnection connection = realUrl.openConnection();
                connection.setRequestProperty(“Content-Type”,“application / json; charset = UTF-8”);
                connection.setRequestProperty(“授權”,令牌);
                connection.connect();
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                字串行;
                while((line = in.readLine())!= null){
                    result + = line;
                }
            }趕上(例外五){
                的System.out.println( “傳送GET請求出現異常!” + E);
                e.printStackTrace();
            }
            //使用finally塊來關閉輸入流
            finally {
                try {
                    if(in!= null){
                        in.close();
                    }
                }趕上(例外E2){
                    e2.printStackTrace();
                }
            }
            返回結果;
        }
        @SuppressWarnings(“未選中”)
        @JsonIgnoreProperties(ignoreUnknown = true)
        public static Apollo jsonToApollo(String json){
             Apollo apollo = new Apollo();
            ObjectMapper mapper = new ObjectMapper();
            try {
                Map <String,Object> map = new HashMap <String,Object>();
                map = mapper.readValue(json,new TypeReference <Map <String,Object >>(){
                });
                
                List <Map <String,Object >> stages =(List <Map <String,Object >>)map.get(“items”);
                List <NamespaceItem> itemList = new ArrayList <NamespaceItem>();
                for(Map <String,Object> stage:stages){
                    NamespaceItem namespace = mapper.readValue(mapper.writeValueAsString(stage),NamespaceItem.class);
                    itemList.add(名稱空間);
                }
                apollo.setToken((String)map.get(“token”)); 
                apollo.setAppId((字串)map.get( “APPID”)); 
                apollo.setEnv((字串)map.get( “ENV”)); 
                apollo.setClusterName((字串)map.get( “CLUSTERNAME”)); 
                apollo.setNamespaceName((字串)map.get( “namespaceName”)); 
                apollo.setComment((字串)map.get( “意見”)); 
                apollo.setFormat((字串)map.get( “格式化”)); 
                String str = String.valueOf(map。
                if(“true”.equalsIgnoreCase(str)){
                    apollo.setIsPublic(“公有”);
                } else {
                    apollo.setIsPublic(“私有”);
                }
                apollo.setDataChangeCreatedBy((String)map.get(“dataChangeCreatedBy”)); 
                apollo.setDataChangeLastModifiedBy((字串)map.get( “dataChangeLastModifiedBy”)); 
                apollo.setDataChangeCreatedTime((字串)map.get( “dataChangeCreatedTime”)); 
                apollo.setDataChangeLastModifiedTime((字串)map.get( “dataChangeLastModifiedTime”)); 
                apollo.setItems(itemList中);


            } catch(JsonMappingException e){
                e.printStackTrace();
            } catch(IOException e){
                e.printStackTrace();
            }
            返回阿波羅;
        }
        
        公共靜態字串postApollo(字串字串,字串令牌的JSONObject jsonParam){
             
              //獲取連線客戶端工具
                CloseableHttpClient的HttpClient = HttpClients.createDefault();

                String entityStr = null;
                CloseableHttpResponse response = null;

                嘗試{

                    //建立POST請求物件
                    HttpPost httpPost = new HttpPost(string);

                  StringEntity entity = new StringEntity(jsonParam.toString(),“utf-8”); //解決中文亂碼問題
                  httpPost.setEntity(entity);

                 //新增請求頭資訊
                    httpPost.addHeader(“Content-Type”,“application / json; charset = UTF-8”);
                    httpPost.addHeader(“授權”,令牌);
                      
                    //執行請求
                    response = httpClient.execute(httpPost);
                    //獲得響應的實體物件
                    
                    HttpEntity entity2 = response.getEntity();
                    //使用Apache提供的工具類進行轉換成字串
                    entityStr = EntityUtils.toString(entity2,“UTF-8”);


                } catch(ClientProtocolException e){
                    System.err.println(“Http協議出現問題”);
                    e.printStackTrace();
                } catch(ParseException e){
                    System.err.println(“解析錯誤”);
                    e.printStackTrace();
                } catch(IOException e){
                    System.err.println(“IO異常”);
                    e.printStackTrace();
                } finally {
                    //釋放連線
                    if(null!= response){
                        try {
                            response.close();
                            httpClient.close();
                        } catch(IOException e){
                            System.err.println(“釋放連接出錯”);
                            e.printStackTrace();
                        }
                    }
                }
             
         返回entityStr;

         }
        
        @SuppressWarnings(“unused”)
        public static String putApollo(String string,String token,JSONObject jsonParam){
             
            CloseableHttpClient closeableHttpClient = HttpClients.createDefault();  
            
            String content = null;
            CloseableHttpResponse response = null;
            
           
            String url =“”;
            
            HttpPut httpput = new HttpPut(url);  
            
            StringEntity entity = new StringEntity(jsonParam.toString(),“utf-8”); //解決中文亂碼問題
            httpput.setEntity(entity);

           //新增請求頭資訊
              httpput.setHeader(“Content-Type”,“application / json; charset = UTF-8”);
              httpput.setHeader(“授權”,令牌);
            
            try {    
             //響應資訊  
                response = closeableHttpClient.execute(httpput);    
                HttpEntity entity2 = response.getEntity();
                
                content = EntityUtils.toString(entity,“UTF-8”);
                
                //使用Apache提供的工具類進行轉換成字串
            } catch(ClientProtocolException e){
                System.err.println(“Http協議出現問題”);
                e.printStackTrace();
            } catch(ParseException e){
                System.err.println(“解析錯誤”)
                e.printStackTrace();
            } catch(IOException e){
                System.err.println(“IO異常”);
                e.printStackTrace();
            } finally {
                //釋放連線
                if(null!= response){
                    try {
                        response.close();
                        closeableHttpClient.close();
                    } catch(IOException e){
                        System.err.println(“釋放連接出錯”);
                        e.printStackTrace();
                    }
                }
            }
         
     返回的內容;
     
    }

}