Java – parsing arrays with multiple types using gson

I want to use gson to parse the following JSON:

[
    [
        "hello",1,[2]
    ],[
        "world",3,[2]
    ]
]

So, this is an array that contains two arrays The two internal arrays themselves are arrays composed of string, int and array types

I'm not sure how to use Java classes to build arrays with three different types (string, array) I started from scratch:

// String json just contains the aforementioned json string.

ArrayList<ArrayList<XXX>> data = new ArrayList<ArrayList<XXX>>();

Type arrayListType = new TypeToken<ArrayList<ArrayList<XXX>>>(){}.getType();

data = gson.fromJson(json,arrayListType);

But where should XXX be? I think it should be an array, but it should be an array with three different data types So how do I model in Java?

Can I help you? Thank you

Solution

Gson has a special processing method, which can deserialize some single component arrays into non array types For example, int data = gson fromJson(“[3]”,int.class); Assign int value 3 to data

Of course, there is no need to deserialize a single component array to a non array type For example, the previous example can be deserialized as int [] data = gson fromJson(“[3]”,int [].

When asked, gson also deserializes non string values to string Apply this to the first example, string data = gson fromJson(“[3]”,String.class); So is work

Note that telling gson to deserialize the first example to object type does not work Object data = gson. fromJson(“[3]”,Object.class); Causing a parsing exception complaint [3] is not an original

For the example of the original problem above, if it is acceptable to treat all values as strings, deserialization becomes simple

// output:
// hello 1 2 
// world 3 2 

public class Foo
{
  static String jsonInput = 
    "[" +
      "[\"hello\",[2]]," +
      "[\"world\",[2]]" +
    "]";

  public static void main(String[] args)
  {
    Gson gson = new Gson();
    String[][] data = gson.fromJson(jsonInput,String[][].class);
    for (String[] data2 : data)
    {
      for (String data3 : data2)
      {
        System.out.print(data3);
        System.out.print(" ");
      }
      System.out.println();
    }
  }
}

Unfortunately, using gson, I can't find a simple deserialization method that can better bind to more specific and mixed types in arrays, because Java doesn't provide syntax for defining mixed type arrays For example, the preferred type of collection in the original problem may be list < list < string, list < int > >, but it is impossible to define it in Java Therefore, you must satisfy list < list < string > > (or string []]), or go to the method of using more "manual" parsing

(yes, Java allows the type declaration of list < Object > >, but object is not a specific type that can be deserialized meaningfully. Moreover, as discussed, trying to deserialize [3] to object causes a parsing exception.)

Minor update: I recently had to refute some rough JSON, including a structure that is not very similar to the original problem I ended up using a custom deserializer to create an object from a cluttered JSON array Similar to the following example

// output: 
// [{MyThreeThings: first=hello,second=1,third=[2]},//  {MyThreeThings: first=world,second=3,third=[4,5]}]

import java.lang.reflect.Type;
import java.util.Arrays;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class FooToo
{
  static String jsonInput =
      "[" +
          "[\"hello\"," +
          "[\"world\",[4,5]]" +
      "]";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(MyThreeThings.class,new MyThreeThingsDeserializer());
    Gson gson = gsonBuilder.create();
    MyThreeThings[] things = gson.fromJson(jsonInput,MyThreeThings[].class);
    System.out.println(Arrays.toString(things));
  }
}

class MyThreeThings
{
  String first;
  int second;
  int[] third;

  MyThreeThings(String first,int second,int[] third)
  {
    this.first = first;
    this.second = second;
    this.third = third;
  }

  @Override
  public String toString()
  {
    return String.format(
        "{MyThreeThings: first=%s,second=%d,third=%s}",first,second,Arrays.toString(third));
  }
}

class MyThreeThingsDeserializer implements JsonDeserializer<MyThreeThings>
{
  @Override
  public MyThreeThings deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context)
      throws JsonParseException
  {
    JsonArray jsonArray = json.getAsJsonArray();
    String first = jsonArray.get(0).getAsString();
    int second = jsonArray.get(1).getAsInt();
    JsonArray jsonArray2 = jsonArray.get(2).getAsJsonArray();
    int length = jsonArray2.size();
    int[] third = new int[length];
    for (int i = 0; i < length; i++)
    {
      int n = jsonArray2.get(i).getAsInt();
      third[i] = n;
    }
    return new MyThreeThings(first,third);
  }
}

The gson user guide covers the deserialization of mixed type collections, similar to the "serializing and deserializing collection with objects of arbitrary types" section

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>