Maison  >  Article  >  Java  >  Comment ajouter automatiquement des propriétés de JSONObject en Java ?

Comment ajouter automatiquement des propriétés de JSONObject en Java ?

WBOY
WBOYavant
2023-08-19 14:41:04617parcourir

Comment ajouter automatiquement des propriétés de JSONObject en Java ?

Un JSONObject est une collection non ordonnée de paires nom/valeur et analyse le texte d'une chaîne pour produire un objet similaire à une carte. Cependant, nous pouvons utiliser la méthode increment() de la classe JSONObject pour incrémenter automatiquement les propriétés de JSONObject. S'il n'existe pas un tel attribut, créez-en un avec la valeur 1. Si une telle propriété existe et qu’il s’agit d’un entier, d’un long, d’un double ou d’un float, alors elle est incrémentée de un.

Syntaxe

public JSONObject increment(java.lang.String key) throws JSONException

Exemple

import org.json.JSONException;
import org.json.JSONObject;
public class IncrementJSONObjectTest {
   public static void main(String[] args) throws JSONException {
<strong>      </strong>JSONObject jsonObj = new JSONObject();
      jsonObj.put("year", 2019);
      jsonObj.put("age", 25);
      System.out.println(jsonObj.toString(3));
      jsonObj.increment("year").increment("age");
      System.out.println(jsonObj.toString(3));
      jsonObj.increment("year").increment("age");
      System.out.println(jsonObj.toString(3));
      jsonObj.increment("year").increment("age");
      System.out.println(jsonObj.toString(3));
   }
}

Sortie

{
 "year": 2019,
 "age": 25
}
{
 "year": 2020,
 "age": 26
}
{
 "year": 2021,
 "age": 27
}
{
 "year": 2022,
 "age": 28
}

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer