Skip to content

Instantly share code, notes, and snippets.

@Muscipular
Created June 13, 2020 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Muscipular/24674f3f05b6729bb66470528387ad58 to your computer and use it in GitHub Desktop.
Save Muscipular/24674f3f05b6729bb66470528387ad58 to your computer and use it in GitHub Desktop.
gson test
package com.example.demo;
import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
String s = "{\n" +
" \"code\": 200,\n" +
" \"data\": {\n" +
" \"specs\": \"[{\\\"name\\\":\\\"容量\\\",\\\"values\\\":[\\\"120G\\\",\\\"260G\\\"]},{\\\"name\\\":\\\"网络型号\\\",\\\"values\\\":[\\\"移动\\\",\\\"联通\\\",\\\"全网通\\\"]}]\"\n" +
" },\n" +
" \"message\": \"请求成功\"\n" +
"}";
Gson gson = new GsonBuilder().registerTypeAdapter(CArray.class, new TypeAd()).create();
A json = gson.fromJson(s, A.class);
CArray specs = json.data.specs;
System.out.println(new Gson().toJson(specs));
// System.out.println(specs);
// JsonArray specObj = gson.fromJson(specs, JsonArray.class);
// System.out.println(specObj.get(0));
}
final class A {
public B data;
}
final class B {
public CArray specs;
}
final class C {
public String name;
public String[] values;
}
final class CArray extends ArrayList<C> {
}
final class TypeAd extends TypeAdapter<CArray> {
@Override
public void write(JsonWriter jsonWriter, CArray c) throws IOException {
}
@Override
public CArray read(JsonReader jsonReader) throws IOException {
String s = jsonReader.nextString();
C[] o = new Gson().fromJson(s, C[].class);
CArray cs = new CArray();
cs.addAll(List.of(o));
return cs;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment