I have not seen an (answered) example on the web which discusses this kind of nested-json-array.
JSON to be parsed:
{
"Field": {
"ObjectsList": [
{
"type": "Num",
"priority": "Low",
"size": 3.43
},
{
"type": "Str",
"priority": "Med",
"size": 2.61
}
]
}
}
I created a class for each 'level' of nested json block. I want to be able to parse the contents of the "ObjectList" array.
Can anyone help me to parse this JSON using Gson in Java?
Any hints or code-snippets would be greatly appreciated.
My approach is the following:
public static void main (String... args) throws Exception
{
URL jsonUrl = new URL("http://jsonUrl.com") // cannot share the url
try (InputStream input = jsonUrl.openStream();
BufferedReader buffReader = new BufferedReader (new InputStreamReader (input, "UTF-8")))
{
Gson gson = new GsonBuilder().create();
ClassA classA = gson.fromJson(buffReader, ClassA.class);
System.out.println(classA);
}
}
}
class ClassA
{
private String field;
// getter & setter //
}
class ClassB
{
private List<ClassC> objList;
// getter & setter //
}
clas ClassC
{
private String type;
private String priority;
private double size;
// getters & setters //
public String printStr()
{
return String.format(type, priority, size);
}
}
The following snippet and source file would help you:
https://github.com/matpalm/common-crawl-quick-hacks/blob/master/links_in_metadata/src/com/matpalm/MetaDataToTldLinks.java#L17
private static ParseResult NO_LINKS = new ParseResult(new HashSet<String>(), 0);
private JsonParser parser;
public static void main(String[] s) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(s[0]));
MetaDataToTldLinks metaDataToTldLinks = new MetaDataToTldLinks();
while (reader.ready()) {
String[] fields = reader.readLine().split("\t");
ParseResult outboundLinks = metaDataToTldLinks.outboundLinks(fields[1]);
System.out.println(tldOf(fields[0]) + " " + outboundLinks.links);
}
}
public MetaDataToTldLinks() {
this.parser = new JsonParser();
}
public ParseResult outboundLinks(String jsonMetaData) {
JsonObject metaData = parser.parse(jsonMetaData.toString()).getAsJsonObject();
if (!"SUCCESS".equals(metaData.get("disposition").getAsString()))
return NO_LINKS;
JsonElement content = metaData.get("content");
if (content == null)
return NO_LINKS;
JsonArray links = content.getAsJsonObject().getAsJsonArray("links");
if (links == null)
return NO_LINKS;
Set<String> outboundLinks = new HashSet<String>();
int numNull = 0;
for (JsonElement linke : links) {
JsonObject link = linke.getAsJsonObject();
if ("a".equals(link.get("type").getAsString())) { // anchor
String tld = tldOf(link.get("href").getAsString());
if (tld == null)
++numNull;
else
outboundLinks.add(tld);
}
}
return new ParseResult(outboundLinks, numNull);
}
public static String tldOf(String url) {
try {
String tld = new URI(url).getHost();
if (tld==null)
return null;
if (tld.startsWith("www."))
tld = tld.substring(4);
tld = tld.trim();
return tld.length()==0 ? null : tld;
}
catch (URISyntaxException e) {
return null;
}
}
public static class ParseResult {
public final Set<String> links;
public final int numNull;
public ParseResult(Set<String> links, int numNull) {
this.links = links;
this.numNull = numNull;
}
}
How about this snippet?:
if (json.isJsonArray()) {
JsonArray array = json.getAsJsonArray();
List<Object> out = Lists.newArrayListWithCapacity(array.size());
for (JsonElement item : array) {
out.add(toRawTypes(item));
}
}
Related
I am using below code to automate REST API.
Please help me to understand how can I put whole json data for sample data mentioned below as the input has arrays whereas till now I used flat jsons without arrays
Method Dummy()
{
RestAssured.baseURI ="http://mydummyURL";
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("id", "THAILAND"); //Issue is with this code
request.header("Content-Type", "application/json");
request.body(requestParams.toJSONString());
Response response = request.post("/EndPoint");
}
where the json body looks like this
{
"tag1": "value1",
"tag2": "value2",
"tag3": {
"tag31": "value31",
"tag32": "value32"
},
"tag4": [{
"domainName": "ABC",
"domainId": "123ABC123",
"domainGUID": "TestMyDomain"
},
{
"domainName": "XYZ",
"domainId": "123XYZ123",
"domainGUID": "TestMyDomain"
}
]
}
ArrayList<JSONObject> array= new ArrayList<JSONObject>();
JSONObject json= new JSONObject();
try {
json.put("key", "value");// your json
} catch (JSONException e) {
e.printStackTrace();
}
array.add(json);
String printjsonarray= array.toString();// pass this into the request
ObjectMapper mapper = new ObjectMapper();
//Create a Java Class for the variables inside array.
JsonArrayData tag4paramVal1 = new JsonArrayData("ABC","123ABC123","TestMyDomain");
JsonArrayData tag4paramVal2 = new JsonArrayData("XYZ","123XYZ123","TestMyDomain");
Object[] tag4ValArray = {tag4paramVal1,tag4paramVal2};
String reqJson = null;
List<String> tag4Data = new ArrayList<String>();
for(Object obj:tag4ValArray){
reqJson = mapper.writeValueAsString(obj);
System.out.println(reqJson);
tag4Data.add(reqJson);
}
System.out.println(tag4Data);
HashMap<String,List<String>> finalReq = new HashMap<String,List<String>>();
finalReq.put("\"tag4\":",tag4Data);
String finalreqString = finalReq.toString();
System.out.println(finalreqString);
finalreqString = finalreqString.replace('=', ' ');
System.out.println(finalreqString);
//Use the above String as a parameter to POST request. You will get your desired JSON array .
//JsonArrayData class code
public class JsonArrayData {
String domainName;
String domainId;
String domainGUID;
public JsonArrayData(String domainName,String domainId,String domainGUID){
this.domainName = domainName;
this.domainId = domainId;
this.domainGUID = domainGUID;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
public String getDomainGUID() {
return domainGUID;
}
public void setDomainGUID(String domainGUID) {
this.domainGUID = domainGUID;
}
}
I want to parse a JSON object from an endpoint (this one here: https://api.coinmarketcap.com/v1/ticker/bitcoin/) and store the value in a variable at a specific attribute, which in this case is the name.
This the ERROR i get:
java.lang.IllegalStateException: Expected a name but was STRING...
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// All your networking logic
// should be here
try {
String u = "https://api.coinmarketcap.com/v1/ticker/bitcoin";
URL coinMarketCapApi = new URL(u);
HttpsURLConnection myConnection = (HttpsURLConnection) coinMarketCapApi.openConnection();
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
if (myConnection.getResponseCode() == 200) {
// Success
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginArray();
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if (key.equals("name")) {
String value = jsonReader.nextName();
break; // Break out of the loop
} else {
jsonReader.skipValue();
}
}
jsonReader.close();
myConnection.disconnect();
} else {
// Error handling code goes here
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
you can convert the InputStream to String and then Create JSONArray from that string. like
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
JSONArray jsonarray = new JSONArray(theString);
This way you don't have to manually construct the array.
Use this depandency for JSONArray
https://mvnrepository.com/artifact/org.json/json
You can fix the problem using gson.
https://github.com/google/gson
com.google.gson.stream.JsonReader jsonReader =
new com.google.gson.stream.JsonReader(new InputStreamReader(responseBody));
ArrayList<Coin> coins = new Gson().fromJson(jsonReader, Coin.class);
coins.forEach(coin -> System.out.println(coin.name));
public class Coin{
private String id;
private String name;
private String symbol;
private int rank;
#SerializedName("price_usd")
private double priceUsd;
...........
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public int getRank() {
return rank;
}
public double getPriceUsd() {
return priceUsd;
}
..........
}
I need to map JSON obj to a class and its arrays to ArrayList in Android and it should have all the children data as well. (with nested arraylists too) and i need to convert updated data list again to jsonobject
my json string is
{
"type": "already_planted",
"crops": [
{
"crop_id": 1,
"crop_name": "apple",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "10"
},
{
"planted_by": "A person"
}
]
},
{
"created_id": "2017-01-30",
"questions": [
{
"plants": "15"
},
{
"planted_by": "B person"
}
]
}
]
},
{
"crop_id": 2,
"crop_name": "Cashew",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "11"
},
{
"planted_by": "c person"
}
]
}
]
}
]
}
First of all, you need to create the class that you are going to map JSON inside.
Fortunately, there is a website that can do it for you here
secondly, you can use google Gson library for easy mapping
1. add the dependency.
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
2. from your object to JSON.
MyData data =new MyData() ; //initialize the constructor
Gson gson = new Gson();
String Json = gson.toJson(data ); //see firstly above above
//now you have the json string do whatever.
3. from JSON to object .
String jsonString =doSthToGetJson(); //http request
MyData data =new MyData() ;
Gson gson = new Gson();
data= gson.fromJson(jsonString,MyData.class);
//now you have Pojo do whatever
for more information about gson see this tutorial.
If you use JsonObject, you can define your entity class as this:
public class Entity {
String type;
List<Crops> crops;
}
public class Crops {
long crop_id;
String crop_name;
List<CropDetail> crop_details;
}
public class CropDetail {
String created_id;
List<Question> questions;
}
public class Question {
int plants;
String planted_by;
}
public void convert(String json){
JsonObject jsonObject = new JsonObject(jsonstring);
Entity entity = new Entity();
entity.type = jsonObject.optString("type");
entity.crops = new ArrayList<>();
JsonArray arr = jsonObject.optJSONArray("crops");
for (int i = 0; i < arr.length(); i++) {
JSONObject crops = arr.optJSONObject(i);
Crops cps = new Crops();
cps.crop_id = crops.optLong("crop_id");
cps.crop_name = crops.optString("crop_name");
cps.crop_details = new ArrayList<>();
JsonArray details = crops.optJsonArray("crop_details");
// some other serialize codes
..........
}
}
So you can nested to convert your json string to an entity class.
Here is how I do it without any packages, this do the work for me for small use cases:
My modal class:
package prog.com.quizapp.models;
import org.json.JSONException;
import org.json.JSONObject;
public class Question {
private String question;
private String correct_answer;
private String answer_a;
private String answer_b;
private String answer_c;
private String answer_d;
public Question() {
}
public Question(String question, String answer_a, String answer_b, String answer_c, String answer_d, String correct_answer) {
this.question = question;
this.answer_a = answer_a;
this.answer_b = answer_b;
this.answer_c = answer_c;
this.answer_d = answer_d;
this.correct_answer = correct_answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getCorrect_answer() {
return correct_answer;
}
public void setCorrect_answer(String correct_answer) {
this.correct_answer = correct_answer;
}
public String getAnswer_a() {
return answer_a;
}
public void setAnswer_a(String answer_a) {
this.answer_a = answer_a;
}
public String getAnswer_b() {
return answer_b;
}
public void setAnswer_b(String answer_b) {
this.answer_b = answer_b;
}
public String getAnswer_c() {
return answer_c;
}
public void setAnswer_c(String answer_c) {
this.answer_c = answer_c;
}
public String getAnswer_d() {
return answer_d;
}
public void setAnswer_d(String answer_d) {
this.answer_d = answer_d;
}
#Override
public String toString() {
return "Question{" +
"question='" + question + '\'' +
", correct_answer='" + correct_answer + '\'' +
", answer_a='" + answer_a + '\'' +
", answer_b='" + answer_b + '\'' +
", answer_c='" + answer_c + '\'' +
", answer_d='" + answer_d + '\'' +
'}';
}
public static Question fromJson(JSONObject obj) throws JSONException {
return new Question(
obj.getString("question"),
obj.getString("answer_a"),
obj.getString("answer_b"),
obj.getString("answer_c"),
obj.getString("answer_d"),
obj.getString("correct_answer"));
}
}
And I have another class to get the json file from assets directory and mapped JsonObject to my model class Question:
package prog.com.quizapp.utils;
import android.content.Context;
import android.util.Log;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import prog.com.quizapp.models.Question;
public class JsonSqlQueryMapper {
private Context mContext;
public JsonSqlQueryMapper(Context context) {
this.mContext = context;
}
private static final String TAG = "JsonSqlQueryMapper";
public JSONObject loadJSONFromAsset() {
String json = null;
try {
InputStream is = mContext.getAssets().open("quiz_app.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
try {
JSONObject quizObject = new JSONObject(json).getJSONObject("quiz");
return quizObject;
} catch (Exception e) {
Log.d(TAG, "loadJSONFromAsset: " + e.getMessage());
return null;
}
}
public ArrayList<Question> generateInsertQueryForJsonObjects() {
ArrayList<Question> questions = new ArrayList<>();
JSONObject jsonObject = loadJSONFromAsset();
try {
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject value = jsonObject.getJSONObject(key);
Question question = Question.fromJson(value.getJSONObject("question_two"));
questions.add(question);
Log.d(TAG, "generateInsertQueryForJsonObjects: " + question.getAnswer_a());
}
} catch (Exception e) {
e.printStackTrace();
}
return questions;
}
}
And in my MainActivity -> onCreate:
JsonSqlQueryMapper mapper = new JsonSqlQueryMapper(MainActivity.this);
mapper.generateInsertQueryForJsonObjects();
To check that everything working as I want. Here is the json file if you want to check https://github.com/Blasanka/android_quiz_app/blob/sqlite_db_app/app/src/main/assets/quiz_app.json
Regards!
I develop an Android application and I have to deserialize a JSON file.
I have these classes:
public class Medicine {
#SerializedName("substanta_activa")
private List<String> active_substance;
#SerializedName("produse")
private List<Product> product;
#SerializedName("dozaj")
private Dosage dosage;
#SerializedName("mentiuni")
private List<String> notes;
#SerializedName("cuvinte_cheie")
private List<String> keyword;
/* + getters and setters */
}
public class Product {
#SerializedName("denumire_comerciala")
private String productName;
#SerializedName("forme_de_prezentare")
private List<String> form;
/* + getters and setters */
}
public class Dosage {
#SerializedName("nounascuti")
private String newborn;
#SerializedName("copii")
private String child;
#SerializedName("adulti")
private String adult;
/* + getters and setters */
}
And I have the following JSON file:
[
{
"substanta_activa": [
"trimebutinum"
],
"produse": [
{
"denumire_comerciala": "Debridat",
"forme_de_prezentare": [
"susp. buvabilă",
"susp. 24mg/5ml în flac 250ml",
"compr 100mg"
]
},
{
"denumire_comerciala": "Ibutin",
"forme_de_prezentare": [
"compr 300mg"
]
},
{
"denumire_comerciala": "Trimebutin",
"forme_de_prezentare": [
"compr 100mg"
]
},
{
"denumire_comerciala": "Colperin",
"forme_de_prezentare": [
"compr 100mg"
]
}
],
"dozaj": {
"nounascuti": "1ml/kg/zi div 3,",
"copii": "1ml/kg/zi div 3, peste 5 ani 3x10ml",
"adulti": "3x1-2 compr/zi, 1x300mg/zi sau 3x1-2 lingură/zi"
},
"mentiuni": [
"se poate administra de la naștere",
"se poate administra amestecat cu apă, lapte",
"10ml conține 6g zahăr"
],
"cuvinte_cheie": [
"gastro",
"colică",
"dureri abdominale funcționale",
"constipație"
]
},
{
"substanta_activa": [
"benzydaminum"
],
"produse": [
{
"denumire_comerciala": "Tantum Verde comprimate",
"forme_de_prezentare": [
"pastile pt supt 3mg"
]
},
{
"denumire_comerciala": "Tantum Verde spray",
"forme_de_prezentare": [
"spray bucofaringian 0,15%, 0,3%"
]
}
],
"dozaj": {
"nounascuti": "contraindicat",
"copii": "2-6 ani: 2-6x1 puf/4kg; >6 sni: 2-6x 4doze sau 3x1 pastila/zi",
"adulti": "2-6x 4puf sau 3x1 pastila/zi"
},
"mentiuni": [
"se admin. max. 7 zile"
],
"cuvinte_cheie": [
"antiseptic, anestezic, antiinflamator, oral, OTC"
]
}
]
I have tried several ways, with GSON and without it as well but with no success. Thank you for your help in advance.
EDIT
A little bit more detail:
I have a MainPageActivity, where I initialize an Inputstream, set a path and call my deserialize method from JSONParser class:
InputStream is = null;
String internalStoragePath = getApplicationContext().getFilesDir().getAbsolutePath();
File fileToInternalStorage = new File(internalStoragePath + "/medicinelist.json");
try {
is = new FileInputStream(fileToInternalStorage);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (is == null) {
is = getResources().openRawResource(R.raw.gyogyszerek);
}
jsonParser = new JSONParser();
try {
medicines = jsonParser.readJsonStream(getApplicationContext(), is);
//medicines = jsonParser.jsonDeserializer(getApplicationContext(), is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
In my JSONParser class, as I have mentioned I have tried several ways to deserialize the JSON input.
Here is the "traditional" way, with Android's built-in JsonReader class (sorry, a little bit long):
public ArrayList readJsonStream(Context applicationContext, InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
try {
return readMedicineArray(reader);
} finally {
reader.close();
}
}
public ArrayList readMedicineArray(JsonReader reader) throws IOException {
ArrayList medicines = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
medicines.add(readMedicine(reader));
}
reader.endArray();
return medicines;
}
public Medicine readMedicine(JsonReader reader) throws IOException {
List active_substance = null;
List product = null;
Dosage dosage = null;
List notes = null;
List keyword = null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("substanta_activa")) {
active_substance = readActiveSubstanceArray(reader);
} else if (name.equals("produse")) {
product = readProductArray(reader);
} else if (name.equals("dozaj")) {
dosage = readDosage (reader);
} else if (name.equals("mentiuni") && reader.peek() != JsonToken.NULL) {
notes= readNotesArray(reader);
} else if (name.equals("cuvinte_cheie") && reader.peek() != JsonToken.NULL) {
keyword = readKeywordArray(reader);
} else {
reader.skipValue();
}
}
reader.endObject();
return new Medicine(active_substance, product, dosage, notes, keyword);
}
public List readActiveSubstanceArray(JsonReader reader) throws IOException {
List active_substance = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
active_substance.add(reader.nextString());
}
reader.endArray();
return active_substance;
}
public List readProductArray(JsonReader reader) throws IOException {
List product = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
product.add(readProduct(reader));
}
reader.endArray();
return product;
}
public Product readProduct(JsonReader reader) throws IOException {
String productName = null;
List form = null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("denumire_comerciala")) {
productName = reader.nextString();
} else if (name.equals("forme_de_prezentare")) {
form = readFormArray(reader);
} else {
reader.skipValue();
}
}
reader.endObject();
return new Product(productName, form);
}
public List readFormArray(JsonReader reader) throws IOException {
List form = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
form.add(reader.nextString());
}
reader.endArray();
return form;
}
public Dosage readDosage(JsonReader reader) throws IOException {
String newborn= null;
String child= null;
String adult= null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("nounascuti")) {
newborn= reader.nextString();
} else if (name.equals("copii")) {
child= reader.nextString();
} else if (name.equals("adulti")) {
adult= reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
return new Dosage(newborn, child, adult);
}
public List readNotesArray(JsonReader reader) throws IOException {
List notes= new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
notes.add(reader.nextString());
}
reader.endArray();
return notes;
}
public List readKeywordArray(JsonReader reader) throws IOException {
List keyword= new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
keyword.add(reader.nextString());
}
reader.endArray();
return keyword;
}
And here is the other way with GSON library:
public ArrayList<Medicine> jsonDeserializer(Context contexts, InputStream in) throws IOException {
Reader reader = new InputStreamReader(in);
ArrayList medicinesList = new ArrayList();
final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();
Medicine[] medicinesArray = new Gson().fromJson(reader, Medicine[].class);
for(int i = 0; i < medicinesArray.length; ++i){
medicinesList.add(medicinesArray[i]);
}
return medicinesList;
}
None of them works, but I don't know what is the problem.
//try this
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Medicine>>() {}.getType();
List<Medicine> medList = gson.fromJson(<YOUR JSON STRING>, listType);
1) Firstly create your classes like this:
public class Produse
{
public String Denumire_comerciala;
public List<String > Forme_de_prezentare;
}
public class Dosage
{
public String Nounascuti;
public String Copii;
public String Adulti;
}
public class RootObject
{
public List<String > Substanta_activa;
public List<Produse> Produse;
public Dosage Dozaj;
public List<String > Mentiuni;
public List<String > Cuvinte_cheie;
}
2) Then use gson like in this way:
Gson _gson = new GsonBuilder().create();
RootObject root= gson.fromJson("*YOUR JSON HERE*", RootObject .class);
Hope it will help.
use this method:
public static <T> T JsonParse(T t, String response)
throws JsonSyntaxException, IOException, XmlPullParserException {
InputStream in = new ByteArrayInputStream(response.getBytes());
JsonReader reader;
reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
GsonBuilder b = new GsonBuilder();
Gson gson = b.create();
t = (T) gson.fromJson(reader, t.getClass());
reader.close();
return t;
}
use this method:
ArrayList<Medicine> arrlist=JsonParse(new Medicine(),JsonResponse);
i hope its useful to you.
We use XStream to serialize objects to JSON and vice versa.
We init xStream like this
XStream xStream = new XStream(new JettisonMappedXmlDriver(new Configuration(), false));
xStream.ignoreUnknownElements();
xStream.setMode(XStream.XPATH_RELATIVE_REFERENCES);
We have test class
public static class TestWOWithBI implements Serializable{
private static final long serialVersionUID = -4720678317857471031L;
private transient String customerNickname;
private transient String customerUuid;
private transient BigInteger discussionId;
private transient String message;
public TestWOWithBI(String customerNickname, String customerUuid, BigInteger discussionId, String message){
this.customerNickname = customerNickname;
this.customerUuid = customerUuid;
this.discussionId = discussionId;
this.message = message;
}
private final void writeObject(final ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(customerNickname);
out.writeObject(customerUuid);
out.writeObject(discussionId);
out.writeObject(message);
}
private final void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException{
in.defaultReadObject();
customerNickname = (String) in.readObject();
customerUuid = (String) in.readObject();
discussionId = (BigInteger) in.readObject();
message = (String) in.readObject();
}
}
After serialization it looks like this:
{
"somethere.ObjectToJSONSerializerTest$TestWOWithBI": {
"#serialization": "custom",
"somethere.ObjectToJSONSerializerTest$TestWOWithBI": {
"default": "",
"string": ["name",
"uuid",
"message"],
"big-int": 1
}
}
}
and deserialization fails with class cast. It was on 1.3.1 and 1.4.7 versions. Looks like bug to me, but may be where is some settings?
UPD:
Seems like org.codehaus.jettison.mapped.MappedXMLStreamWriter.JSONPropertyObject#withProperty
if(old != null) {
JSONArray values;
// Convert an existing property to an array
// and append to the array
if (old instanceof JSONArray) {
values = (JSONArray)old;
} else {
values = new JSONArray();
values.put(old);
}
values.put(value);
object.put(property.getKey(), values);
} else if(getSerializedAsArrays().contains(property.getKey())) {
JSONArray values = new JSONArray();
values.put(value);
object.put(property.getKey(), values);
} else {
// Add the property directly.
object.put(property.getKey(), value);
}
It just group elements of same type.