Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » U++ Library support » U++ Core » Custom array Jsonize
Custom array Jsonize [message #36226] Mon, 14 May 2012 18:38 Go to next message
koldo is currently offline  koldo
Messages: 3354
Registered: August 2008
Senior Veteran
Hello all

I wanted to Jsonize a custom array but I do not know how to do it. Could you help me? Smile

This very simple and rude code saves correctly but it does not load the values:

#include <Core/Core.h>

using namespace Upp;

struct MyVector {
	MyVector() 			{sz = 0;}
	void resize(int _sz) 		{data.Alloc(_sz); sz = _sz;}
	int size() 			{return sz;}
	double &operator()(int i) 	{return data[i];}
	
	Buffer<double> data;
	int sz;	
};

void Jsonize(JsonIO &xml, MyVector &vec) {
	int sz;
	if(xml.IsStoring()) 
		sz = vec.size();
	xml("size", sz);
	if(xml.IsLoading()) 
		vec.resize(sz);
	for(int r = 0; r < sz; r++) 
		xml("", vec(r));	
}

CONSOLE_APP_MAIN
{
	StdLogSetup(LOG_COUT);
	
	MyVector v, w;
	
	v.resize(3);
	for (int i = 0; i < 3; ++i)
		v(i) = i;
	
	String jso = StoreAsJson(v);
	LoadFromJson(w, jso);
	
	LOG(w(2));
	getchar();
}


I have also tried code based in JsonizeArray() implementation but in my case it raises exceptions.

void JsonizeArray(JsonIO& io, MyVector & array)
{
	if(io.IsLoading()) {
		const Value& va = io.Get();
		array.resize(va.GetCount());
		for(int i = 0; i < va.GetCount(); i++) {
			JsonIO jio(va[i]);
			Jsonize(jio, array(i));
		}
	}
	else {
		Vector<Value> va;
		va.SetCount(array.size());
		for(int i = 0; i < array.size(); i++) {
			JsonIO jio;
			Jsonize(jio, array(i));
			jio.Put(va[i]);
		}
		io.Set(ValueArray(va));	// It raises an "IsStoring() && !map" exception here
	}
}


Best regards
Iñaki

[Updated on: Mon, 14 May 2012 18:39]

Report message to a moderator

Re: Custom array Jsonize [message #36229 is a reply to message #36226] Tue, 15 May 2012 00:46 Go to previous message
koldo is currently offline  koldo
Messages: 3354
Registered: August 2008
Senior Veteran
Well, this works well but is less efficient Smile :

void Jsonize(JsonIO &xml, MyVector &vec) {
	Vector<double> vector;
	if(xml.IsStoring()) {
		vector.SetCount(vec.size());
		for (int i = 0; i < vec.size(); ++i)
			vector[i] = vec(i);
		xml("vector", vector);
	} else {
		xml("vector", vector);
		vec.resize(vector.GetCount());
		for (int i = 0; i < vec.size(); ++i)
			vec(i) = vector[i];
	}
}


Best regards
Iñaki
Previous Topic: Jsonize problem with Null
Next Topic: File locking and Serialization
Goto Forum:
  


Current Time: Thu Mar 28 12:56:38 CET 2024

Total time taken to generate the page: 0.01214 seconds