Regex for entire words - java

I need some help creating a regex. The String value is:
{"meta":[{"this_id":"111111"},{"this_id":"222222"},{"this_id":"333333"}],"type":"Account"}
I want to create a list with all the ids, so element[0] would be 111111, element[1] would be 222222, for example. I would also like to at least be able to isolate the type and set that to a String.
Can I receive some help on this? I tried to do
String[] tokens = stringToBreakUp.split(":");
Then I was just focused on all the tokens after the 2nd element in that list. I am not sure how to search list based on a key. I think I need some sort of key. But I am new at doing these things.

Just use \\d+ to get all the numbers. Check demo
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(yourString);
while (m.find()) {
// print m.group() to get all ids
}

Use any JSON parsing library such as GSON or Jackson and convert it into Java Object.
Sample code using GSON library:
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(jsonString, type);
// just iterate the map and get the desired value
Sample code using Jackson library:
JSONObject obj = new JSONObject(s);
JSONArray jsonArray = obj.getJSONArray("meta");
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.getJSONObject(i).get("this_id"));
}
output:
111111
222222
333333

I absolutely agree that the RegEx is not an appropriate tool to parse JSON, but this simple test will help you to do it.
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.testng.Assert.assertEquals;
public class SimpleTest {
#Test
public void test() throws Exception {
String str = "{\"meta\":[{\"this_id\":\"111111\"},{\"this_id\":\"222222\"},{\"this_id\":\"333333\"}],\"type\":\"Account\"}";
Pattern idPattern = Pattern.compile("\\{\"this_id\"\\s*\\:\\s*\"(\\d+)\"\\}");
Matcher idMatcher = idPattern.matcher(str);
Collection<String> ids = new ArrayList<>();
while (idMatcher.find()) {
ids.add(idMatcher.group(1));
}
assertEquals(Arrays.asList("111111", "222222", "333333"), ids);
Pattern typePattern = Pattern.compile("\"type\"\\s*\\:\\s*\"([^\"]+)\"");
Matcher typeMatcher = typePattern.matcher(str);
String type = typeMatcher.find() ? typeMatcher.group(1) : null;
assertEquals("Account", type);
}
}

Related

Concatenate all JSON key-value pairs into a String

I have input:
{
"Id": 200,
"TimeStamp": 1596466800,
"Animal": "cat"
}
I need to concatenate all key-value pairs in one String
I need output:
"Id200Timestamp1596466800Animalcat"
Usually you use a third-party library for parsing JSON. There are several. The below code uses Gson.
Note that the below code is not terribly robust, it assumes that there are no nested elements and that the values are all primitives. That is what you specifically asked for, i.e. specific input and specific output, and I am posting a solution that achieves what you specifically asked for.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import java.util.Map;
import java.util.Set;
public class GsonTst0 {
public static void main(String[] args) {
String json = "{ \"Id\": 200, \"TimeStamp\": 1596466800, \"Animal\": \"cat\"}";
JsonElement root = JsonParser.parseString(json);
if (root.isJsonObject()) {
JsonObject jsonObj = root.getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entries = jsonObj.entrySet();
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, JsonElement> entry : entries) {
sb.append(entry.getKey());
JsonElement elem = entry.getValue();
JsonPrimitive prim = elem.getAsJsonPrimitive();
if (prim.isNumber()) {
sb.append(prim.getAsBigDecimal());
}
else {
sb.append(prim.getAsString());
}
}
System.out.println(sb);
}
}
}
Running the above code prints the following:
Id200TimeStamp1596466800Animalcat

Wrong order of data when converting a JTable to JSON [duplicate]

I've a problem trying to make my page printing out the JSONObject in the order i want. In my code, I entered this:
JSONObject myObject = new JSONObject();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");
However, when I see the display on my page, it gives:
JSON formatted string: [{"success":"NO", "userid":"User 1", "bid":24.23}]
I need it in the order of userid, amount, then success. Already tried re-ordering in the code, but to no avail. I've also tried .append....need some help here thanks!!
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at https://www.json.org/
An object is an unordered set of
name/value pairs
As a consequence,
JSON libraries are free to rearrange the order of the elements as they see fit.
This is not a bug.
I agree with the other answers. You cannot rely on the ordering of JSON elements.
However if we need to have an ordered JSON, one solution might be to prepare a LinkedHashMap object with elements and convert it to JSONObject.
#Test
def void testOrdered() {
Map obj = new LinkedHashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Ordered Json : %s", json.toString())
String expectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
assertEquals(expectedJsonString, json.toString())
JSONAssert.assertEquals(JSONSerializer.toJSON(expectedJsonString), json)
}
Normally the order is not preserved as below.
#Test
def void testUnordered() {
Map obj = new HashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Unordered Json : %s", json.toString(3, 3))
String unexpectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
// string representation of json objects are different
assertFalse(unexpectedJsonString.equals(json.toString()))
// json objects are equal
JSONAssert.assertEquals(JSONSerializer.toJSON(unexpectedJsonString), json)
}
You may check my post too: http://www.flyingtomoon.com/2011/04/preserving-order-in-json.html
u can retain the order, if u use JsonObject that belongs to com.google.gson :D
JsonObject responseObj = new JsonObject();
responseObj.addProperty("userid", "User 1");
responseObj.addProperty("amount", "24.23");
responseObj.addProperty("success", "NO");
Usage of this JsonObject doesn't even bother using Map<>
CHEERS!!!
Real answer can be found in specification, json is unordered.
However as a human reader I ordered my elements in order of importance. Not only is it a more logic way, it happened to be easier to read. Maybe the author of the specification never had to read JSON, I do.. So, Here comes a fix:
/**
* I got really tired of JSON rearranging added properties.
* Specification states:
* "An object is an unordered set of name/value pairs"
* StackOverflow states:
* As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit.
* I state:
* My implementation will freely arrange added properties, IN SEQUENCE ORDER!
* Why did I do it? Cause of readability of created JSON document!
*/
private static class OrderedJSONObjectFactory {
private static Logger log = Logger.getLogger(OrderedJSONObjectFactory.class.getName());
private static boolean setupDone = false;
private static Field JSONObjectMapField = null;
private static void setupFieldAccessor() {
if( !setupDone ) {
setupDone = true;
try {
JSONObjectMapField = JSONObject.class.getDeclaredField("map");
JSONObjectMapField.setAccessible(true);
} catch (NoSuchFieldException ignored) {
log.warning("JSONObject implementation has changed, returning unmodified instance");
}
}
}
private static JSONObject create() {
setupFieldAccessor();
JSONObject result = new JSONObject();
try {
if (JSONObjectMapField != null) {
JSONObjectMapField.set(result, new LinkedHashMap<>());
}
}catch (IllegalAccessException ignored) {}
return result;
}
}
from lemiorhan example
i can solve with just change some line of lemiorhan's code
use:
JSONObject json = new JSONObject(obj);
instead of this:
JSONObject json = (JSONObject) obj
so in my test code is :
Map item_sub2 = new LinkedHashMap();
item_sub2.put("name", "flare");
item_sub2.put("val1", "val1");
item_sub2.put("val2", "val2");
item_sub2.put("size",102);
JSONArray itemarray2 = new JSONArray();
itemarray2.add(item_sub2);
itemarray2.add(item_sub2);//just for test
itemarray2.add(item_sub2);//just for test
Map item_sub1 = new LinkedHashMap();
item_sub1.put("name", "flare");
item_sub1.put("val1", "val1");
item_sub1.put("val2", "val2");
item_sub1.put("children",itemarray2);
JSONArray itemarray = new JSONArray();
itemarray.add(item_sub1);
itemarray.add(item_sub1);//just for test
itemarray.add(item_sub1);//just for test
Map item_root = new LinkedHashMap();
item_root.put("name", "flare");
item_root.put("children",itemarray);
JSONObject json = new JSONObject(item_root);
System.out.println(json.toJSONString());
JavaScript objects, and JSON, have no way to set the order for the keys. You might get it right in Java (I don't know how Java objects work, really) but if it's going to a web client or another consumer of the JSON, there is no guarantee as to the order of keys.
Download "json simple 1.1 jar" from this https://code.google.com/p/json-simple/downloads/detail?name=json_simple-1.1.jar&can=2&q=
And add the jar file to your lib folder
using JSONValue you can convert LinkedHashMap to json string
For those who're using maven, please try com.github.tsohr/json
<!-- https://mvnrepository.com/artifact/com.github.tsohr/json -->
<dependency>
<groupId>com.github.tsohr</groupId>
<artifactId>json</artifactId>
<version>0.0.1</version>
</dependency>
It's forked from JSON-java but switch its map implementation with LinkedHashMap which #lemiorhan noted above.
As all are telling you, JSON does not maintain "sequence" but array does, maybe this could convince you:
Ordered JSONObject
For Java code, Create a POJO class for your object instead of a JSONObject.
and use JSONEncapsulator for your POJO class.
that way order of elements depends on the order of getter setters in your POJO class.
for eg. POJO class will be like
Class myObj{
String userID;
String amount;
String success;
// getter setters in any order that you want
and where you need to send your json object in response
JSONContentEncapsulator<myObj> JSONObject = new JSONEncapsulator<myObj>("myObject");
JSONObject.setObject(myObj);
return Response.status(Status.OK).entity(JSONObject).build();
The response of this line will be
{myObject : {//attributes order same as getter setter order.}}
The main intention here is to send an ordered JSON object as response. We don't need javax.json.JsonObject to achieve that. We could create the ordered json as a string.
First create a LinkedHashMap with all key value pairs in required order. Then generate the json in string as shown below.
Its much easier with Java 8.
public Response getJSONResponse() {
Map<String, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A", "1");
linkedHashMap.put("B", "2");
linkedHashMap.put("C", "3");
String jsonStr = linkedHashMap.entrySet().stream()
.map(x -> "\"" + x.getKey() + "\":\"" + x.getValue() + "\"")
.collect(Collectors.joining(",", "{", "}"));
return Response.ok(jsonStr).build();
}
The response return by this function would be following:
{"A":"1","B":"2","C":"3"}
Underscore-java uses linkedhashmap to store key/value for json. I am the maintainer of the project.
Map<String, Object> myObject = new LinkedHashMap<>();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");
System.out.println(U.toJson(myObject));
I found a "neat" reflection tweak on "the interwebs" that I like to share.
(origin: https://towardsdatascience.com/create-an-ordered-jsonobject-in-java-fb9629247d76)
It is about to change underlying collection in org.json.JSONObject to an un-ordering one (LinkedHashMap) by reflection API.
I tested succesfully:
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
private static void makeJSONObjLinear(JSONObject jsonObject) {
try {
Field changeMap = jsonObject.getClass().getDeclaredField("map");
changeMap.setAccessible(true);
changeMap.set(jsonObject, new LinkedHashMap<>());
changeMap.setAccessible(false);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
[...]
JSONObject requestBody = new JSONObject();
makeJSONObjLinear(requestBody);
requestBody.put("username", login);
requestBody.put("password", password);
[...]
// returned '{"username": "billy_778", "password": "********"}' == unordered
// instead of '{"password": "********", "username": "billy_778"}' == ordered (by key)
Just add the order with this tag
#JsonPropertyOrder({ "property1", "property2"})
Not sure if I am late to the party but I found this nice example that overrides the JSONObject constructor and makes sure that the JSON data are output in the same way as they are added. Behind the scenes JSONObject uses the MAP and MAP does not guarantee the order hence we need to override it to make sure we are receiving our JSON as per our order.
If you add this to your JSONObject then the resulting JSON would be in the same order as you have created it.
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
import lombok.extern.java.Log;
#Log
public class JSONOrder {
public static void main(String[] args) throws IOException {
JSONObject jsontest = new JSONObject();
try {
Field changeMap = jsonEvent.getClass().getDeclaredField("map");
changeMap.setAccessible(true);
changeMap.set(jsonEvent, new LinkedHashMap<>());
changeMap.setAccessible(false);
} catch (IllegalAccessException | NoSuchFieldException e) {
log.info(e.getMessage());
}
jsontest.put("one", "I should be first");
jsonEvent.put("two", "I should be second");
jsonEvent.put("third", "I should be third");
System.out.println(jsonEvent);
}
}
Just use LinkedHashMap to keep de order and transform it to json with jackson
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
stats.put("aaa", "aaa");
stats.put("bbb", "bbb");
stats.put("ccc", "ccc");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
System.out.println(json);
maven dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10.7</version>
</dependency>
I just want the order for android unit tests that are somehow randomly changing overtime with this cool org.json.JSONObject, even thou it looks like it uses linked map but probably depends on api you compile it with or something, so it has different impl. with different android api probably.
I would suggest something like this:
object Json {
#SuppressLint("DiscouragedPrivateApi")
fun Object() = org.json.JSONObject().apply {
runCatching {
val nameValuePairs: Field = javaClass.getDeclaredField("nameValuePairs")
nameValuePairs.isAccessible = true
nameValuePairs.set(this, LinkedHashMap<String, Any?>())
}.onFailure { it.printStackTrace() }
}
}
Usage:
val jsonObject = Json.Object()
...
This is just some possibility I use it little differently so I modified it to post here. Sure gson or other lib is another option.
Suggestions that specification is bla bla are so shortsighted here, why you guys even post it, who cares about 15 years old json spec, everyone wants it ordered anyway.

How to convert a string to JSONArray

I am hitting an api and getting a string response. The response is something like this
"["VU","Vanuatu",["Pacific/Efate","(GMT+11:00) Efate"],"VN","Vietnam",["Asia/Saigon","(GMT+07:00) Hanoi"]]"
And i want to convert this string into a json array of below type
[{"id":"VN","name":"Vanuatu","timezones":[{"id":Pacific/Efate,"name":"(GMT+11:00) Efate}]},"id":"VN","name":"Vietnam",[{"id":"Asia/Saigon","name":"(GMT+07:00) Hanoi"}]]
Can someone help
Looking at your String response, I've created a regular expression that will create four groups out of your response.
DEMO
Assuming that your output would come always in groups of four (i.e., id, name and timezones_id, timezones_name), this regular expression, would extract 4 groups out of the input string that you've provided:
Regex:
"([^"]*)",\s*"([^"]*)",\s*\["([^"]*)",\s*"([^"]*)"\]
Matches
Match 1
Full match 1-56 `"VU", "Vanuatu", ["Pacific/Efate", "(GMT+11:00) Efate"]`
Group 1. 2-4 `VU`
Group 2. 8-15 `Vanuatu`
Group 3. 20-33 `Pacific/Efate`
Group 4. 37-54 `(GMT+11:00) Efate`
Match 2
Full match 58-111 `"VN", "Vietnam", ["Asia/Saigon", "(GMT+07:00) Hanoi"]`
Group 1. 59-61 `VN`
Group 2. 65-72 `Vietnam`
Group 3. 77-88 `Asia/Saigon`
Group 4. 92-109 `(GMT+07:00) Hanoi`
 
Now once you've extracted these 4 groups, You can simply add appropriately in ArrayList and List and create JSONArray out of those lists.
The following program is self-explanatory with the inputs and outputs.
Input
["VU","Vanuatu",["Pacific/Efate","(GMT+11:00) Efate"],"VN","Vietnam",["Asia/Saigon","(GMT+07:00) Hanoi"]]
Output
[{"timezones":{"name":"(GMT+11:00) Efate","id":"Pacific/Efate"},"name":"Vanuatu","id":"VU"},{"timezones":{"name":"(GMT+07:00) Hanoi","id":"Asia/Saigon"},"name":"Vietnam","id":"VN"}]
Formatted Output
[{
"id" : "VU",
"name" : "Vanuatu",
"timezones" : {
"name" : "(GMT+11:00) Efate",
"id" : "Pacific/Efate"
}
}, {
"id" : "VN",
"name" : "Vietnam",
"timezones" : {
"name" : "(GMT+07:00) Hanoi",
"id" : "Asia/Saigon"
}
}
]
Code
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
public class Test
{
public static void main(String[] args) throws IOException, JSONException {
String serverResponse = "[\"VU\", \"Vanuatu\", [\"Pacific/Efate\", \"(GMT+11:00) Efate\"], \"VN\", \"Vietnam\", [\"Asia/Saigon\", \"(GMT+07:00) Hanoi\"]]";
Map<String, Object> prop, innerProp;
List<Object> arr = new ArrayList<>(), obj;
String pattern = "\"([^\"]*)\",\\s*\"([^\"]*)\",\\s*\\[\"([^\"]*)\",\\s*\"([^\"]*)\"\\]";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(serverResponse);
while (m.find()) {
prop = new HashMap<>();
prop.put("id", m.group(1));
prop.put("name", m.group(2));
innerProp = new HashMap<>();
innerProp.put("id", m.group(3));
innerProp.put("name", m.group(4));
prop.put("timezones", innerProp);
arr.add(prop);
}
JSONArray jsonArray = new JSONArray(arr);
System.out.println(jsonArray.toString());
}
}
An option you have is to first create a JSONArray off of the string, and then read elements 3 by 3 from that array to create your output:
public static void main(String[] args) {
String input = "[\"VU\",\"Vanuatu\",[\"Pacific/Efate\",\"(GMT+11:00) Efate\"],\"VN\",\"Vietnam\",[\"Asia/Saigon\",\"(GMT+07:00) Hanoi\"]]";
JSONArray inputArray = new JSONArray(input);
JSONArray outputArray = new JSONArray();
for (int i = 0; i < inputArray.length(); i += 3) {
JSONObject obj = readCountry(inputArray, i);
outputArray.put(obj);
}
System.out.println(outputArray);
}
private static JSONObject readCountry(JSONArray array, int index) {
JSONObject country = new JSONObject();
country.put("id", array.getString(index));
country.put("name", array.getString(index + 1));
country.put("timezones", readTimeZones(array.getJSONArray(index + 2)));
return country;
}
private static JSONArray readTimeZones(JSONArray array) {
JSONArray timezones = new JSONArray();
JSONObject timezone = new JSONObject();
timezone.put("id", array.getString(0));
timezone.put("name", array.getString(1));
timezones.put(timezone);
return timezones;
}
You may add some error handling to fail gracefully or even recover with best effort if the input doesn't match.

read a string in JSON format in JAVA

I want to read a string as a JSON format(it doesn't have to be JSON, but it seems like JSON format) and represent it to a hashMap(key : Keyword, value : COUNT)
for example, assume I have a String.
String s ={"Welcome":1,"Hi":2,"Hello":1,"Jin":1};
Then, make it classification.(for Hashmap key --> word, value--> number). final result would be something like as below.
HashMap<String,String> result;
result.get("Jin"); // output : 1
result.get("Hi"); // output : 2
but my codes, it doesn't go with right way.
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
JSONArray array = new JSONArray();
array.add(obj);
System.out.println(array.get(0)); //output: {"Welcome":1,"Hi":2,"Hello":1,"Jin":1}
can it be possible with JSON? or should I split them one by one? (such as split them with "," first and ":" ... so on)
Please give me your kind advice.
Try with below code snippet.
public static void main(final String[] args) throws ParseException {
String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
JSONParser parser = new JSONParser();
HashMap<String, Long> obj = (HashMap<String, Long>) parser.parse(s);
for(String key : obj.keySet()) {
System.out.println("Key:" + key + " value:" + obj.get(key));
}
}
You can use org.json to fulfill your requirement.
E.g.
String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
JSONObject result = new JSONObject(s);
System.out.println(result.get("Jin")); // output : 1
System.out.println(result.get("Hi")); // output : 2
The easiest to achieve this is by using JACKSON parsers.
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(s, new TypeReference<HashMap<String, String>>() {
});
map.forEach((k, v) -> System.out.println("Key is " + k + " value is " + v));
Prints :
Key is Hi value is 2
Key is Hello value is 1
Key is Welcome value is 1
Key is Jin value is 1
Its a json object not an array...
try this one :
JSONObject jsonObj = new JSONObject(jsonString.toString());
Use Google JSON i.e gson library(2.6.2) and your problem will be solved.
Please have a look to the following code
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class StackOverFlowQuestionset {
public static void main(String[] args) {
String s ="{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
HashMap<String,String> result=new HashMap<String,String>();
Gson gson = new Gson();
JsonElement jsonElement = gson.fromJson(s, JsonElement.class);
JsonObject jsonObject = jsonElement.getAsJsonObject();
Set<Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();
for(Entry<String, JsonElement> entry:jsonEntrySet){
result.put(entry.getKey(), entry.getValue().toString());
}
System.out.println(result.get("Jin"));
System.out.println(result.get("Welcome"));
System.out.println(result.get("Hi"));
}
}

Parsing JSON array

I'm using GSON for parsing JSON response.
Unfortunately the WebApi on the server has quite untypical JSON objects.
I need to parse Attachments array from this JSON (there can be more attachments):
{"htmlMessage":"text","Attachments":{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg","contentDisposition":"attachment","size":86070}}}
Where 8216096_0 is attachments id.
I can't do it with Gson (or I don't know how) so I'm trying to do it with JSONObjects:
// parse attachments
JSONObject attachmentsJson = result.getJSONObject("Attachments");
Then I have one JSONObject with an array of attachments, but I don't know how to get them to the ArrayList from JSONObject because the key value isn't static but generated id..
Thank you
//EDIT:
Thanks to all guys for helping! My final solution looks like this especially thanks to #Jessie A. Morris and his final answer!
List<AttachmentModel> attachmentsList = new ArrayList<AttachmentModel>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
AttachmentModel attachmentModel = new AttachmentModel();
attachmentModel = gson.fromJson(attachment.getValue().getAsJsonObject().toString(), AttachmentModel.class);;
attachmentModel.setmUid(attachment.getKey());
attachmentsList.add(attachmentModel);
}
Okay, I've changed my example a little bit and am certain that this does work correctly (I just tested it):
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by jessie on 14-07-09.
*/
public class TestGson {
private static String JSON = "{\"htmlMessage\":\"text\",\"Attachments\":{\"8216096_0\":{\"content\":null,\"filename\":\"plk.jpg\",\"contentType\":\"image/jpeg\",\"contentDisposition\":\"attachment\",\"size\":86070}}}\n";
public static void main(String[] args) {
JsonObject json = new JsonParser().parse(JSON).getAsJsonObject();
JsonObject attachments = json.getAsJsonObject("Attachments");
List<JsonObject> attachmentsList = new ArrayList<JsonObject>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
attachmentsList.add(attachment.getValue().getAsJsonObject());
}
System.out.println("attachmentsList at the end? " + attachmentsList);
}
}
I'm not completely sure if this really works:
final Map<String,JSONObject> attachmentsJson = (Map<String,JSONObject>) jsonArray.getJSONObject("Attachments");
for(String attachmentId : attachmentsJson.keySet()) {
final JSONObject attachmentJson = attachmentsJson.get(attachmentId);
}
The "Attachments" obj in your example is not an array.
Json arrays are denoted by [....].
"Attachments" is a Json object holding an inner object called "8216096_0".
so to get the inner values do as follows:
JSONObject attachmentsJson = result.getJSONObject("Attachments");
JSONObject inner = attachmentsJson.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
Finally, and for example sake, I will add the code for processing a (real) Json array:
{"htmlMessage":"text",
"Attachments":[{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
{"8216096_1":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
]
}
It will go like this:
JSONArray attachmentsJson = result.getJSONObject("Attachments");
int len = attachmentsJson.length();
for (int i = 0; i < len; i++) {
JSONObject elem = attachmentsJson.getJSONObject(i); // <------ get array element
JSONObject inner = elem.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
}
..Or similar, depending on your Json's exact format.

Categories

Resources