I have a JSONParser method like this :
public ArrayList<Meaning> parseMeaning (JSONObject object)
{
ArrayList<Meaning> arrayList = new ArrayList<Meaning>();
try
{
JSONObject value = object.getJSONObject("Value");
JSONArray meaningArray = value.getJSONArray("Meanings");
JSONObject meaningobj = null;
for(int i = 0; i < meaningArray.length(); i++) {
meaningobj = meaningArray.getJSONObject(i);
Meaning myMeaning = new Meaning();
myMeaning.MeaningID = meaningobj.getInt("MeaningID");
myMeaning.Type1 = meaningobj.getInt("Type1");
myMeaning.Type2= meaningobj.getInt("Type2");
arrayList.add(myMeaning);
}
}
catch (JSONException e)
{
Log.d("JSONParser=>parseMeaning", e.getMessage());
}
return arrayList;
}
My meaning class is like this :
public class Meaning {
public int MeaningID;
public Integer Type1;
public Integer Type2;
}
When I run the code, some JSON Objects don't have Type2 value (because they were null in the database). So I get this exception :
D/JSONParser=>parseMeaning﹕ No value for Type2
Can you tell me how I should handle such situations when there is no value for a field? Thanks.
You can use has method of JSONObject.
E.g. :
if(meaningobj.has("Type2")){
myMeaning.Type2= meaningobj.getInt("Type2");
}
Related
Here is my code for the parsing the JSON file and printing too.:
public class JsonpJsonParser implements IparseJson {
public static void main(String[] args) {
IparseJson parser = new JsonpJsonParser();
try (FileInputStream in = new FileInputStream("data.json")) {
List<QueryResultBean1> results = parser.parseJson(in);
for (QueryResultBean1 result : results) {
System.out.println(result.getHeader().getRequest_id());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public List<QueryResultBean1> parseJson(InputStream in) {
JsonReader reader = Json.createReader(in);
JsonObject json = reader.readObject();
reader.close();
// parse the json object, return something
List<QueryResultBean1> results = new ArrayList<QueryResultBean1>();
JsonArray items = json.getJsonArray("header");
for (JsonValue item : items) {
if (item instanceof JsonObject) {
QueryResultBean1 result = createBean((JsonObject)item);
results.add(result);
}
}
return results;
}
public QueryResultBean1 createBean(JsonObject json) {
QueryResultBean1 bean = new QueryResultBean1();
// you could also change tags to a List
JsonArray array = json.getJsonArray("header");
String[] h1 = new String[array.size()];
for (int i = 0; i < h1.length; i++) {
h1[i] = array.getString(i);
}
bean.setTags(h1);
retrun bean}
Ive tried executing this code for the JSON file:
"header":[
{
"request_id":1547706529870,
"file_name":"Sm-1547706529870.xlsm",
"file_type":"CIR",
"status":"NEW",
"is_end":false
}
GOT THE ERROR AS:
`Exception in thread "main" java.lang.NullPointerExceptionat com.example.webjson.com.webjson.p1.JsonpJsonParser.createBean(JsonpJsonParser.java:60)
NEED HELP TO PARSE THE DATA.JSON FILE IN JAVA
In the code below:
JsonArray array = json.getJsonArray("header");
You are trying to retrieve an JsonArray from String?, you should retrieve the element in array using an index like:
JsonArray array = json.getJsonArray(0);
This is the JSON array:
{
"server_response": [{
"Total": "135",
"Paid": "105",
"Rest": "30"
}]
}
So, how can i get the object names? I want to put them in separate TextView.
Thanks.
Put this out side everything. I mean outside onCreate() and all.
private <T> Iterable<T> iterate(final Iterator<T> i){
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return i;
}
};
}
For getting the names of objects :
try
{
JSONObject jsonObject = new JSONObject("{" +"\"server_response\": [{" +"\"Total\": \"135\"," +"\"Paid\": \"105\"," +"\"Rest\": \"30\"" +"}]"+"}";);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject object = jsonArray.getJSONObject(0);
for (String key : iterate(object.keys()))
{
// here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
Toast.makeText(HomeActivity.this, ""+key, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps :)
My suggestion:
Go to this website:
Json to pojo
Get your pojo classes and then use them in Android.
All you need to do is to use Gson.fromGson(params here).
One of your params is the class that you created using the online schema.
You can use jackson ObjectMapper to do this.
public class ServerResponse {
#JsonProperty("Total")
private String total;
#JsonProperty("Paid")
private String paid;
#JsonProperty("Rest")
private String rest;
//getters and setters
//toString()
}
//Now convert json into ServerResponse object
ObjectMapper mapper = new ObjectMapper();
TypeReference<ServerResponse> serverResponse = new TypeReference<ServerResponse>() { };
Object object = mapper.readValue(jsonString, serverResponse);
if (object instanceof ServerResponse) {
return (ServerResponse) object;
}
JSONObject jsonObject = new JSONObject("Your JSON");
int Total = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Total");
int Paid = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Paid");
int Rest = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Rest");
I would like to mask certain elements of JSON and print to logs. Masking can be either by substituting by dummy data or removing the key pair .Is there a utility to do the masking in Java ?
E.g.,
given JSON:
{
"key1":"value1",
"key2":"value2",
"key3":"value3",
}
mask key 2 alone and print JSON:
{
"key1":"value1",
"key2":"xxxxxx",
"key3":"value3",
}
or
{
"key1":"value1",
"key3":"value3",
}
input will be JSON object or array type in string format. Here the maskable keys only static otherwise input string will dynamic.
public final class MaskPIData {
/**
* Mask able keywords mentioned here. It should be in LOWER CASE.
*/
private static final Set<String> MASKABLE_KEYS = new HashSet<>(Arrays.asList(
"email",
"emails",
"phone",
"pin",
"password",
"phonenumber",
"moneys"));
private static final String MASKING_VALUE = "****";
private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();
private MaskPIData() {
super();
}
private static boolean isValidSet(Set<String> set) {
return set != null && !set.isEmpty();
}
private static boolean isKnownPrimitiveWrapperModel(Object obj) {
return obj == null || obj instanceof String || obj instanceof Integer || obj instanceof Long
|| obj instanceof Double;
}
#SuppressWarnings("unchecked")
private static JSONObject maskingForJsonObject(Set<String> maskableKeys, JSONObject input) {
if (!isValidSet(maskableKeys) || input == null) {
return input;
}
Map<String, Object> inputMap = (Map<String, Object>) input;
Map<String, Object> caseInsensitiveInputMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveInputMap.putAll(inputMap);
for (Map.Entry<String, Object> entryPair : caseInsensitiveInputMap.entrySet()) {
if (entryPair.getValue() instanceof JSONArray) {
JSONArray jsonArr = (JSONArray) caseInsensitiveInputMap.get(entryPair.getKey());
maskingForArray(maskableKeys, entryPair.getKey(), jsonArr);
caseInsensitiveInputMap.put(entryPair.getKey(), jsonArr);
} else if (entryPair.getValue() instanceof JSONObject) {
JSONObject jsonObj = (JSONObject) caseInsensitiveInputMap.get(entryPair.getKey());
caseInsensitiveInputMap.put(entryPair.getKey(), maskingForJsonObject(maskableKeys, jsonObj));
} else if (entryPair.getKey() != null && maskableKeys.contains(entryPair.getKey().toLowerCase())) {
caseInsensitiveInputMap.put(entryPair.getKey(), MASKING_VALUE);
}
}
return OBJECTMAPPER.convertValue(caseInsensitiveInputMap, JSONObject.class);
}
#SuppressWarnings("unchecked")
private static JSONArray maskingForArray(Set<String> maskableKeys, String key,
JSONArray jsonArr) {
JSONArray toRet = jsonArr;
for (int idx = 0; idx < toRet.size(); idx++) {
Object obj = toRet.get(idx);
if (isKnownPrimitiveWrapperModel(obj)) {
if (key != null && maskableKeys.contains(key.toLowerCase())) {
toRet.remove(idx);
toRet.add(idx, MASKING_VALUE);
}
} else {
JSONObject jsonObjFromArray = (JSONObject) toRet.get(idx);
JSONObject maskedJsonObj = maskingForJsonObject(maskableKeys, jsonObjFromArray);
toRet.remove(idx);
toRet.add(idx, maskedJsonObj);
}
}
return toRet;
}
public static String doMask(String input) {
String maskedData = input;
if (maskedData != null && !maskedData.trim().isEmpty()) {
try {
if (new JSONParser().parse(maskedData) instanceof JSONObject) {
JSONObject maskedOutput = maskingForJsonObject(MASKABLE_KEYS,
(JSONObject) new JSONParser().parse(maskedData));
maskedData = OBJECTMAPPER.writeValueAsString(maskedOutput);
} else if (new JSONParser().parse(maskedData) instanceof JSONArray) {
JSONArray maskedOutput = maskingForArray(MASKABLE_KEYS, null, (JSONArray) new JSONParser().parse(maskedData));
maskedData = OBJECTMAPPER.writeValueAsString(maskedOutput);
}
} catch (Exception e) {
// to do - Error while masking data
}
}
return maskedData;
}
public static void main(String args[]) {
String input = "{\"item\":{\"test\":\"test\",\"phone\":\"993244\",\"email\":\"mail#mail.com\"}}";
System.out.println(doMask(input));
}
You could use jackson to convert json to map, process map and convert map back to json.
For example:
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public void mask() throws IOException {
String jsonString = "{\n" +
" \"key1\":\"value1\",\n" +
" \"key2\":\"value2\",\n" +
" \"key3\":\"value3\"\n" +
"}";
Map<String, Object> map;
// Convert json to map
ObjectMapper mapper = new ObjectMapper();
try {
TypeReference ref = new TypeReference<Map<String, Object>>() { };
map = mapper.readValue(jsonString, ref);
} catch (IOException e) {
System.out.print("cannot create Map from json" + e.getMessage());
throw e;
}
// Process map
if(map.containsKey("key2")) {
map.put("key2","xxxxxxxxx");
}
// Convert back map to json
String jsonResult = "";
try {
jsonResult = mapper.writeValueAsString(map);
} catch (IOException e) {
System.out.print("cannot create json from Map" + e.getMessage());
}
System.out.print(jsonResult);
Overview; i need to create a json from a List to store in a sqlLite database. When i try to create the json Eclipse gets me an error that the variable List must be static. If this variable changed to static my application shows incorrect results and it's not a good thing. This is the class in which i create the json
public class Soluzione {
public String durata;
public List<Corsa> corse;
public Soluzione() {
corse = new ArrayList<Corsa>();
}
#Override
public String toString() {
StringBuilder str = new StringBuilder();
for (Corsa corsa : corse) {
if (str.length() > 0)
str.append('\n');
str.append(corsa.toString());
}
return str.toString();
}
public static JSONObject CreateJSon(List<Corsa> corse)
{
JSONObject jObj = new JSONObject();
try
{
Corsa prima = Soluzione.corse.get(0);
Corsa ultima = Soluzione.corse.get(corse.size()-1);
jObj.put("oraPartenza", prima.oraPartenza);
jObj.put("oraArrivo", ultima.oraArrivo);
jObj.put("partenza", prima.partenza);
jObj.put("arrivo", ultima.arrivo);
} catch (Exception e) { e.printStackTrace(); }
return jObj;
}
}
It is ambiguous between your field corse and the parameter of your method Create JSON.
Do not make method static and remove parameter
public JSONObject CreateJSon()
{
JSONObject jObj = new JSONObject();
try
{
Corsa prima = Soluzione.corse.get(0);
Corsa ultima = Soluzione.corse.get(corse.size()-1);
jObj.put("oraPartenza", prima.oraPartenza);
jObj.put("oraArrivo", ultima.oraArrivo);
jObj.put("partenza", prima.partenza);
jObj.put("arrivo", ultima.arrivo);
} catch (Exception e) { e.printStackTrace(); }
return jObj;
}
EDIT :
so if you want to keep CreateJSon static, rename the parameter name to avoid ambiguity then :
Soluzione soluzione = new Soluzione();
Soluzione.CreateJSon (soluzione.corse);
OR you want to remove static attribute and you can remove parameter and you do :
Soluzione soluzione = new Soluzione();
soluzione.CreateJSon ();
I'm fairly new to JSON parsing in Java but when I try and parse this JSON String & find out it's "ID", it repeats the same one twice.
[
{"id":"{ID1}","time":123},
{"id":"{ID2}","time":124}
]
This is my Java code:
// v = json string, c = "id"
String output = v.replace("[", "").replace("]", "");
JSONObject obj = new JSONObject(output);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < obj.length(); i++){
System.out.println(obj.getString(c));
list.add(obj.getString(c));
}
return list.get(1);
it returns ID1 twice or more. Please help
Your JSON represents an array - so that's how you should parse it. You can then easily get the id property from each JSONObject within the array. For example:
import org.json.*;
public class Test {
public static void main(String[] args) throws JSONException {
String json =
"[{\"id\":\"{ID1}\",\"time\":123}, {\"id\":\"{ID2}\",\"time\":124}]";
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
System.out.println(o.getString("id"));
}
}
}
Output:
{ID1}
{ID2}
I fixed my code by using it as a JSONArray(Thanks #HotLicks)
JSONArray obj = new JSONArray(v);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < obj.length(); i++){
Logger.WriteOutput(obj.getJSONObject(i).getString(c), Logger.LogLevel.Info);
}
Try this :
// This line is useless
// String output = v.replace("[", "").replace("]", "");
JSONArray arr = new JSONArray(output);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < arr.length(); i++){
System.out.println(arr.getJSONObject(i).getString(c));
list.add(arr.getJSONObject(i).getString(c));
}
First create a java bean for your json (for example here):
public class Item {
#JsonProperty("id")
private String id;
#JsonProperty("time")
private Integer time;
public final String getId() {
return id;
}
public final void setId(String id) {
this.id = id;
}
public final Integer getTime() {
return time;
}
public final void setTime(Integer time) {
this.time = time;
}
}
If you are using Jackson Java JSON-processor, you can create a List from JSON-String this way:
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Item> items = objectMapper.readValue(
yourJSONString,
objectMapper.getTypeFactory().constructCollectionType(List.class, Item.class));
for (Item item : items) {
System.out.println(item.getId());
}
} catch (IOException e) {
e.printStackTrace();
}
use below code
String v = "[{\"id\":\"ID1\",\"time\":123},{\"id\":\"ID2\",\"time\":124}]";
String c = "id";
JSONArray obj = null;
try {
obj = new JSONArray(v);
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < obj.length(); i++) {
JSONObject j = (JSONObject) obj.get(i);
System.out.println(j.getString(c));
list.add(j.getString(c));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
note that i have slightly corrected the json structure too
before
[
{"id":"{ID1}","time":123},
{"id":"{ID2}","time":124}
]
after
[
{"id":"ID1","time":123},
{"id":"ID2","time":124}
]