Lily
Lily

Reputation: 707

how to replace the last index item of JSON

I have a JSON in the following format. I want to replace the Nutrition at the last index with Title using java code.

Current Format

{
    "nutrients" : [{

        "Nutrient" : "Alcohol, ethyl",
        "Amount" : " 3.9",
        "Unit" : " g"

    }, {

        "Nutrient" : "Fiber",
        "Amount" : " 0.0",
        "Unit" : " g"

    }, {

        "Nutrient" : "Alcoholic beverage, BUDWEISER, regular, beer"

    }] 
}

Required Format

{
    "nutrients" : [{

        "Nutrient" : "Alcohol, ethyl",
        "Amount" : " 3.9",
        "Unit" : " g"

    }, {

        "Nutrient" : "Fiber",
        "Amount" : " 0.0",
        "Unit" : " g"

    }, {

        "Title" : "Alcoholic beverage, BUDWEISER, regular, beer"

    }]
}

Upvotes: 2

Views: 461

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79425

You can do it by using String#lastIndexOf and String#substring. Note that both of these methods have two variants.

public class Main {
    public static void main(String[] args) {
        String json = "{\n" + "    \"nutrients\" : [{\n" + "\n" + "        \"Nutrient\" : \"Alcohol, ethyl\",\n"
                + "        \"Amount\" : \" 3.9\",\n" + "        \"Unit\" : \" g\"\n" + "\n" + "    }, {\n" + "\n"
                + "        \"Nutrient\" : \"Fiber\",\n" + "        \"Amount\" : \" 0.0\",\n"
                + "        \"Unit\" : \" g\"\n" + "\n" + "    }, {\n" + "\n"
                + "        \"Nutrient\" : \"Alcoholic beverage, BUDWEISER, regular, beer\"\n" + "\n" + "    }] \n"
                + "}";

        int i = json.lastIndexOf("\"Nutrient\"");

        // (string before last "Nutrient") + ("Title") + (string after last "Nutrient")
        String result = json.substring(0, i) + "\"Title\"" + json.substring(i + "\"Nutrient\"".length());

        System.out.println(result);
    }
}

Output:

{
    "nutrients" : [{

        "Nutrient" : "Alcohol, ethyl",
        "Amount" : " 3.9",
        "Unit" : " g"

    }, {

        "Nutrient" : "Fiber",
        "Amount" : " 0.0",
        "Unit" : " g"

    }, {

        "Title" : "Alcoholic beverage, BUDWEISER, regular, beer"

    }] 
}

Upvotes: 1

Aman Gulati
Aman Gulati

Reputation: 31

This looks fairly easy, if you use jackson a well known java library for json. once you have this on your classpath(may be using the jar or the gradle dependency,etc) you can now do this a couple of ways. the easiest of which is to probably use objectmapper to parse this data into a pojo and then manipulate the pojo. or otherwise you could save extra cost and computation by may be parsing this into a JsonNode.

//try to use this instance as much as you can(JACKSON-101)
ObjectMapper mapper = new ObjectMapper();
    final JsonNode jsonNode = mapper.readTree("parse_your_json_string_here");
    /**
     * to get to the nutrients i use `at` because it is nullsafe :D although if performance is a
     * concern and `/nutrients` is a common use case you may want to precompile the pointer using <code>
     * JsonPointer nutsPointer = JsonPointer.compile("/nutrients");
     * </code>
     */
    final JsonNode temp = jsonNode.at("/nutrients");
    // once done just to be sure we have the right data check that its an arrayNode :D
    if (temp.isArray()) {
      // if true cast it :D
      ArrayNode arrayNode = (ArrayNode) temp;
      final JsonNode nutrientsNodeToModify = arrayNode.path(arrayNode.size() - 1);
      if (nutrientsNodeToModify.isObject()) {
        ObjectNode nutrientsNode = (ObjectNode) nutrientsNodeToModify;
        nutrientsNode.set("Title", nutrientsNode.at("/Nutrient"));
        nutrientsNode.remove("Nutrient");
      }
    }

Upvotes: 1

KunLun
KunLun

Reputation: 3227

You can achieve this using Jackson.

Needed libs:

  1. Jackson Core: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.11.0
  2. Jackson Databind: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.11.0

But you can't change field name. Instead you can add a new one and remove the other.

public static void main(String[] args) throws JsonProcessingException {

    String json = ...;

    //transform string to jsonnode
    JsonNode jsonNode = (new ObjectMapper()).readTree(json);

    //get nutrients array node
    JsonNode nutrientsNode = jsonNode.get("nutrients");
    int lastIndex = nutrientsNode.size() - 1;

    //get last node from nutrients and cast to objectnode
    ObjectNode lastNutrientObject = (ObjectNode)nutrientsNode.get(lastIndex);

    //get Nutrient field value from last nutrient
    JsonNode nutrientField = lastNutrientObject.get("Nutrient");

    //remove Nutriend field from last nutrient
    lastNutrientObject.remove("Nutrient");

    //add Title field with node nutrientField into last nutrient
    lastNutrientObject.set("Title", nutrientField);

    System.out.println(jsonNode.toPrettyString());

}

Upvotes: 1

Related Questions