json格式與SpringMvc接收json列表的問題

同學們都知道:

一、json的格式如下:{     platformId:3,     buyerId:13626,     aftersaleId:1708193111000001,     orderNo:170809311032603,     requiredServices:10,     providerType:4,     assemblyServiceDescription:'77777',     providerId:13800,     sku:10007248      }

json數組格式如下:[{"itemId":10000280,"cid":1004862}] 

總的來說就是,用 [ ] 來包裹多個 { }   ,  用 : 來表示鍵值對  , 用 ,來連接多個鍵值對,這樣簡單的json用逗號與花括號來表示,數組類型的json用方括號包裹多個花括號,花括號內多個鍵值對來表示.

通常用 [ ] 來表示數組 ,用 { } 來表示非數組(對象)

 

二、那麼怎麼接受數組類型的json呢,我們在用springMvc接受參數的時候,可以用@RequestParam(value = "platformId",required = true) Long platformId來接受單個參數,用@RequestBody List<List<String>> skuList來接受對象或者簡單數組,用@ModelAttribute ItemCategoryStashVo itemCategoryStashVo 來接受對象,(ModelAttribute在跨域的時候,例如feign調用,會丟失值,所以feign調用可以用requestbody)

那如何接受對象類型List列表呢, 前臺可以傳json數組, 後臺直接接受json數組字符串,然後把字符串解析成對象集合:代碼如下

SpringMvc接參-->@ApiParam(value="商品與類目ID") @RequestParam String itemsIndex

轉換-->

String itemsIndex="jsonarraystr";

if(null != itemsIndex) {

            Gson gson = new Gson();
            List<ItemAuthorizationVo> itemAuthorizationVoList = gson.fromJson(itemsIndex, new TypeToken<List<ProviderCollectionItemResultVo>>() {}.getType());
        } 

(  import com.google.gson.Gson;     import com.google.gson.reflect.TypeToken;)

 

三、那對象如何轉換爲json串呢

JSONArray cidsArray = JSONArray.fromObject(cids);
        JSONArray sortDatasArray = JSONArray.fromObject(sortDatas);
        ObjectMapper objectMapper = new ObjectMapper();

for (int i = 0; i < cidsArray.size(); i++) {
                cid = objectMapper.readValue(cidsArray.getString(i), Long.class);
                categoryIds.add(cid);
            }

( import net.sf.json.JSONArray; )

 

四、Gson與Jackson反序列化的區別

 我們後臺接受整參數時會接受整個對象的json字符串,我們用Gson轉化成我們需要的java對象,需要注意的兩點是,Gson轉化時間戳字段時候會報錯,jackson轉化時間戳字段是不報錯的,可以查看下面的例子,

 

package com.jd.ecc.b2b.item.service.item;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.Date;

@Slf4j
public class JacksonTest {


    private static ObjectMapper objectMapper = new ObjectMapper();


    @Test
    public void test() {

        String result = JacksonTest.encode(new Date());

        log.info("=========:{}", result);

        Date date = JacksonTest.decode("1517827150000", Date.class);

        log.info("=========:date", date);
    }

    public static String encode(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 將json string反序列化成對象
     *
     * @param json
     * @param valueType
     * @return
     */
    public static <T> T decode(String json, Class<T> valueType) {
        try {
            return objectMapper.readValue(json, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 將json array反序列化爲對象
     *
     * @param json
     * @param typeReference
     * @return
     */
    public static <T> T decode(String json, TypeReference<T> typeReference) {
        try {
            return (T) objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

 

下面是常用的一些轉換示例:

 JSONObject jsonObj = JSONObject.fromObject(Object); //把 對象 轉換成 json String  {"key":111 , "value":23456}
 JSONArray jsonArray = JSONArray.fromObject(jsonObj.get("itemInfo")); //把 List類型對象 或者jsonString 轉換成 json 數組 String 上面說過json數組是[]來表示
 ItemBrand itemBrand = new ObjectMapper.readValue(jsonArray.getString(0) 'String', ItemBrand.class); //把 String 轉換成對象

 String brandInfoStr = new ObjectMapper.writeValueAsString(Object); //把 對象(對象可以是list或者非list) 轉換爲 json String
 JSONArray jsonArray = JSONArray.fromObject(brandInfoStr); //把 String 轉換成 json 數組 String
 QueryBrandByBrandIdResultVo =new ObjectMapper.readValue(jsonArray.getString(i), QueryBrandByBrandIdResultVo.class); //將 json String 轉換爲 對象,請注意當String中有屬性左邊賦值對象沒有這個屬性時會報錯Unrecognized field

 PlatformAttributeParams platformAttributeParams = new Gson().fromJson(String, PlatformAttributeParams.class); //將 json String 轉換爲 對象
List<TradeItemSkuPrice> list= (List<TradeItemSkuPrice>) new Gson().fromJson(tradeItemSkuPriceListVoStr, new TypeToken<List<TradeItemSkuPrice>>() {}.getType()); //將 json 數組 String 轉換爲 List子對象
 List<String> keysArray = JSON.parseArray(String, String.class); //將 json 數組 String 轉換爲 List 對象
 List<?> values = <alibaba>JSON.parseArray("[{key:1233434, value:badfdsf}, {key:1233434, value:badfdsf}]", Object.class); //將 json 數組 String 轉換爲 List 對象
 List<Map<String, Object>> params = new ArrayList<>();
 values.forEach(it -> { params.add((Map<String, Object>)it) });

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章