Example #1
0
/*
HRESULT CBDictionary::UTF82VARIANT(const char *pstr, int nCount, VARIANT* pvar)
{
	if (pvar==NULL) return E_INVALIDARG;

	if (nCount == 0)
		nCount = lstrlen(pstr);
	
	int _nTempCount = ::MultiByteToWideChar(65001, 0, pstr, nCount, NULL, NULL);
	CComBSTR bstr(_nTempCount);

	if (bstr==NULL) return E_OUTOFMEMORY;
	::MultiByteToWideChar(65001, 0, pstr, nCount, bstr, _nTempCount);

	pvar->vt = VT_BSTR;
	pvar->bstrVal = bstr.Detach();
	return S_OK;
}

LPSTR CBDictionary::BSTR2UTF8(BSTR strData, int *pCount)
{
	UINT strLen = SysStringByteLen(strData);
	int _nTempCount = ::WideCharToMultiByte(65001, 0, strData, strLen / 2, NULL, 0, NULL, NULL);
	LPSTR pstr = new char[_nTempCount+1];
	::WideCharToMultiByte(65001, 0, strData, strLen / 2, pstr, _nTempCount, NULL, NULL);
	pstr[_nTempCount] = 0;
	if (pCount!=NULL) *pCount = _nTempCount;
	return pstr;
}
*/
STDMETHODIMP CBDictionary::JSON_join( IStream *pStrm, int indent, CAtlArray<void*> &arrObjects)
{
	POSITION pos;
	CRBMap<CBVariant, CComVariant>::CPair* pPair;
	HRESULT hr;
	ULONG n1;
	int indent1 = indent >= 0 ? indent + 1 : indent;

	hr = pStrm->Write(L"{\r\n", (indent != -1 ? 3 : 1) * sizeof(WCHAR), &n1);
	if(FAILED(hr))return hr;

	CBLock l(&m_cs);
	arrObjects.Add((void *)(IDispatch *)this);

	pos = m_mapItems.GetHeadPosition();
	while(pos)
	{
		pPair = (CRBMap<CBVariant, CComVariant>::CPair*)m_mapItems.GetNext(pos);

		hr = JSON_putTabs(pStrm, indent1);
		if(FAILED(hr))return hr;

		if(pPair->m_key.vt == VT_BSTR)
			hr = JSON_putVariant(pStrm, &pPair->m_key, indent1, arrObjects);
		else
		{
			CComVariant var;

			hr = ::VariantChangeType(&var, (VARIANTARG*)&pPair->m_key, VARIANT_ALPHABOOL, VT_BSTR);
			if(FAILED(hr))return hr;

			hr = JSON_putVariant(pStrm, &var, indent1, arrObjects);
		}
		if(FAILED(hr))return hr;

		if(indent != -1)
			hr = pStrm->Write(L": ", 2 * sizeof(WCHAR), &n1);
		else
			hr = pStrm->Write(L":", 1 * sizeof(WCHAR), &n1);
		if(FAILED(hr))return hr;

		hr = JSON_putVariant(pStrm, &pPair->m_value, indent1, arrObjects);
		if(FAILED(hr))return hr;

		if(pos)
			hr = pStrm->Write(L",\r\n", (indent != -1 ? 3 : 1) * sizeof(WCHAR), &n1);
		else if(indent != -1)
			hr = pStrm->Write(L"\r\n", 2 * sizeof(WCHAR), &n1);
		if(FAILED(hr))return hr;
	}

	hr = JSON_putTabs(pStrm, indent);
	if(FAILED(hr))return hr;
	hr = pStrm->Write(L"}", 1 * sizeof(WCHAR), &n1);
	if(FAILED(hr))return hr;

	arrObjects.RemoveAt(arrObjects.GetCount()-1);
	return S_OK;
}