Home > Blockchain >  How to define this JSON as a JAVA Object
How to define this JSON as a JAVA Object

Time:04-14

I'm receiving the following JSON:

[
    669124,
    [
        [
            40135,
            5,
            0.68395602
        ],
        [
            40134,
            1,
            0.03737
        ]
    ]
]

How can I turn this into a JAVA Object?

CodePudding user response:

How about...

public class Outer {
   private int field1;
   private List<Inner> field2;
}

public class Inner {
   private int field1;
   private int field2;
   private double field3;
}

And then you just parse the json and read them into these classes?

CodePudding user response:

The problem with this particular JSON is that it is a list of different types. The first element is a number (int), the second is a 2-dimensional array of numbers, some ints and some doubles.

So if you tried to parse this to a custom Java object, you would get at best List<Object>, or just Object.

I believe you want to parse it into a JSON tree. There are several libraries, Jackson is the most popular by far.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class JsonTest {
    String JSON = "[\n"  
        "    669124,\n"  
        "    [\n"  
        "        [\n"  
        "            40135,\n"  
        "            5,\n"  
        "            0.68395602\n"  
        "        ],\n"  
        "        [\n"  
        "            40134,\n"  
        "            1,\n"  
        "            0.03737\n"  
        "        ]\n"  
        "    ]\n"  
        "]";
    
    @Test
    public void testJson() throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        JsonNode doc = om.readTree(JSON);
    
        assertThat(doc.isArray(), is(true));
        JsonNode element1 = doc.get(0);
        assertThat(element1.isInt(), is(true));
        assertThat(element1.asInt(), is(669124));
    
        JsonNode element2 = doc.get(1);
        assertThat(element2.isArray(), is(true));
    
        assertThat(element2.get(0).get(0).intValue(), is(40135));
        assertThat(element2.get(0).get(1).intValue(), is(5));
        assertThat(element2.get(0).get(2).doubleValue(), is(0.68395602));
    
        assertThat(element2.get(1).get(0).intValue(), is(40134));
        assertThat(element2.get(1).get(1).intValue(), is(1));
        assertThat(element2.get(1).get(2).doubleValue(), is(0.03737));
    }
}
  • Related