I am trying to read JSON string using gson into a Java program. In the sample code below - the Java program has 3 object classes. The data in the json string will have a vari
This is the code - that works based on @hurricane suggestion.
package newpackage;
import java.util.List;
import com.google.gson.*;
public class jsonsample {
public static void main(String[] args) throws ClassNotFoundException {
String jsonstring = "{'TableA':["
+ "{'field_A1':'A_11'},"
+ "{'field_A1':'A_12'}"
+ "],"
+ "'TableB':["
+ "{'field_B1':'B_11','field_B2':'B_12','field_B3':['abc','def']},"
+ "{'field_B1':'B_21','field_B2':'B_22','field_B3':['mno','xyz']}"
+ "],"
+ "'TableC':["
+ "{'field_C1':'C_11','field_C2':'C_12','field_C3':'C_13'},"
+ "{'field_C1':'C_21','field_C2':'C_22','field_C3':'C_23'}"
+ "]}";
jsonstring = jsonstring.replace('\'', '"');
RootObject root = new GsonBuilder().create().fromJson(jsonstring, RootObject.class);
for (int i=0; i < root.TableA.size(); i++){
System.out.println(root.TableA.get(i));
}
for (int i=0; i < root.TableB.size(); i++){
System.out.println(root.TableB.get(i));
}
for (int i=0; i < root.TableC.size(); i++){
System.out.println(root.TableC.get(i));
}
}
public class TableA
{
public String field_A1;
@Override
public String toString() {
return ("Table A" + " " + this.field_A1);
}
}
public class TableB{
public String field_B1;
public String field_B2;
public List field_B3;
@Override
public String toString() {
return ("Table B" + " " + this.field_B1 + " " + this.field_B2 + " " + this.field_B3);
}
}
public class TableC{
public String field_C1;
public String field_C2;
public String field_C3;
@Override
public String toString() {
return ("Table C" + " " + this.field_C1 + " " + this.field_C2 + " " + this.field_C3);
}
}
public class RootObject{
public List TableA;
public List TableB;
public List TableC;
}
}
The output for the above is:
Table A A_11
Table A A_12
Table B B_11 B_12 [abc, def]
Table B B_21 B_22 [mno, xyz]
Table C C_11 C_12 C_13
Table C C_21 C_22 C_23